DB2使用Hibernate攔截器實現臟讀(with ur)
來源:程序員人生 發(fā)布時間:2014-10-03 08:00:01 閱讀次數:3657次
工作需要,最近要讓開發(fā)的系統(tǒng)底層適應的數據庫增加對DB2的支持,雖然使用了DB2,但是就性能考慮,和業(yè)務需要。查詢不需要進行事務控制,也就是DB2的多種事務安全級別,在查詢時,不需要關注更新和插入。因此需要查詢支持臟讀。每條查詢的sql語句后面都要增加with ur選項。
在網上找了很久,很多人在問,但是沒有結果。最后,在google找到解決辦法,使用hibernate攔截器,進行攔截。下面是代碼:
import org.hibernate.EmptyInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* hibernate配置DB2時,為了防止高事務安全級別對查詢造成影響,因此查詢需要單獨制定with ur。
* 此類是hibernate攔截器,用于給select的查詢末尾增加with ur選項,以防止查詢時鎖住數據庫庫。
* @author superxb
*
*/
public class DB2Interceptor extends EmptyInterceptor {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory
.getLogger(DB2Interceptor.class);
@Override
public String onPrepareStatement(String str) {
// sql字符串全部轉換成小寫
String compstr = str.toLowerCase();
// 所有的select語句,只要是不包含with ur的。在后面都加上with ur
if (compstr.matches("^select.*") && !compstr.matches(".*for update.*")) {
if (!compstr.matches(".*with ur.*")) {
str += " with ur ";
logger.debug("Appending "WITH UR" to query.");
}
}
return str;
}
}
攔截器創(chuàng)建好后,配置在hibernate的sessionFactory即可。配置參考如下:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource" />
</property>
<!-- 專門針對DB2增加的攔截器,在所有的sql后面增加 whit ur控制事務級別 -->
<property name="entityInterceptor">
<bean class="interceptor.DB2Interceptor" />
</property>
……
……
如上配置之后。默認的,只要是select開頭的sql語句,其中未包含with ur的話,就會在末尾增加with ur,以確保事務安全級別,實現hibernate映射DB2數據庫時,能夠進行臟讀操作。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈