JDBC có cơ chế này được đặt tên Query Timeout, bạn có thể gọi phương thức của đối tượng setQueryTime java.sql.Statement để kích hoạt thiết lập này.
Hibernate không thể thực hiện việc này theo cách thống nhất.
Nếu ứng dụng của bạn truy xuất lại kết nối JDBC vi java.sql.DataSource, câu hỏi có thể được giải quyết dễ dàng.
chúng tôi có thể tạo một DateSourceWrapper để kết nối proxy mà làm setQueryTimeout cho mỗi tuyên bố nó tạo ra.
Mã ví dụ dễ đọc, tôi sử dụng một số lớp học sử dụng lò xo để trợ giúp điều này.
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;
}
}
Bây giờ chúng ta có thể sử dụng QueryTimeoutConfiguredDataSource này để bao bọc của bạn tồn tại DataSource để thiết lập truy vấn Timeout mỗi khi Báo cáo minh bạch!
mùa xuân cấu hình file:
<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>
Bạn đang sử dụng hồ bơi kết nối. – Bozho
Yup, sử dụng C3PO – malaverdiere