JDBC diesen Mechanismus hat auch können Sie setQueryTime Methode java.sql.Statement Objekt aufrufen, diese Einstellung zu aktivieren.
Hibernate kann dies nicht in einheitlicher Weise tun.
Wenn Ihre Anwendung die JDBC-Verbindung vi java.sql.DataSource reaktiviert, kann die Frage leicht gelöst werden.
können wir einen DateSourceWrapper Proxy Connnection erstellen, die für jede erstellte Anweisung SetQueryTimeout setzen.
Der Beispielcode ist leicht zu lesen, ich benutze einige Spring-Util-Klassen, um dies zu unterstützen.
public class QueryTimeoutConfiguredDataSource extends DelegatingDataSource {
private int queryTimeout;
public QueryTimeoutConfiguredDataSource(DataSource dataSource) {
super(dataSource);
}
// override this method to proxy created connection
@Override
public Connection getConnection() throws SQLException {
return proxyWithQueryTimeout(super.getConnection());
}
// override this method to proxy created connection
@Override
public Connection getConnection(String username, String password) throws SQLException {
return proxyWithQueryTimeout(super.getConnection(username, password));
}
private Connection proxyWithQueryTimeout(final Connection connection) {
return proxy(connection, new InvocationHandler() {
//All the Statement instances are created here, we can do something
//If the return is instance of Statement object, we set query timeout to it
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object object = method.invoke(connection, args);
if (object instanceof Statement) {
((Statement) object).setQueryTimeout(queryTimeout);
}
return object;
});
}
private Connection proxy(Connection connection, InvocationHandler invocationHandler) {
return (Connection) Proxy.newProxyInstance(
connection.getClass().getClassLoader(),
ClassUtils.getAllInterfaces(connection),
invocationHandler);
}
public void setQueryTimeout(int queryTimeout) {
this.queryTimeout = queryTimeout;
}
}
Jetzt können wir diese QueryTimeoutConfiguredDataSource benutzen, um Ihre Wrapper existiert Datasource Abfrage-Timeout transparent für jede Anweisung zu setzen!
Frühling Konfigurationsdatei:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<bean class="com.stackoverflow.QueryTimeoutConfiguredDataSource">
<constructor-arg ref="dataSource"/>
<property name="queryTimeout" value="1" />
</bean>
</property>
</bean>
Verwenden Sie einen Verbindungspool. – Bozho
Yup, mit C3PO – malaverdiere