时间:2021-07-01 10:21:17 帮助过:69人阅读
工作需要,最近要让开发的系统底层适应的数据库增加对DB2的支持,虽然使用了DB2,但是就性能考虑,和业务需要。查询不需要进行事务控制,也就是DB2的多种事务安全级别,在查询时,不需要关注更新和插入。因此需要查询支持脏读。每条查询的sql语句后面都要增
工作需要,最近要让开发的系统底层适应的数据库增加对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数据库时,能够进行脏读操作。
- <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
- <property name="dataSource">
- <ref local="dataSource">
- </ref></property>
- <!-- 专门针对DB2增加的拦截器,在所有的sql后面增加 whit ur控制事务级别 -->
- <property name="entityInterceptor">
- <bean class="interceptor.DB2Interceptor">
- </bean></property>
- ……
- ……</bean>