工作需要,最近要让开发的系统底层适应的数据库增加对db2的支持,虽然使用了db2,但是就性能考虑,和业务需要。查询不需要进行事务控制,也就是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; }}
拦截器创建好后,配置在hibernate的sessionfactory即可。配置参考如下:
…………
如上配置之后。默认的,只要是select开头的sql语句,其中未包含with ur的话,就会在末尾增加with ur,以确保事务安全级别,实现hibernate映射db2数据库时,能够进行脏读操作。
