当前位置:Gxlcms > mysql > DB2使用Hibernate拦截器实现脏读(withur)

DB2使用Hibernate拦截器实现脏读(withur)

时间:2021-07-01 10:21:17 帮助过:69人阅读

工作需要,最近要让开发的系统底层适应的数据库增加对DB2的支持,虽然使用了DB2,但是就性能考虑,和业务需要。查询不需要进行事务控制,也就是DB2的多种事务安全级别,在查询时,不需要关注更新和插入。因此需要查询支持脏读。每条查询的sql语句后面都要增

工作需要,最近要让开发的系统底层适应的数据库增加对DB2的支持,虽然使用了DB2,但是就性能考虑,和业务需要。查询不需要进行事务控制,也就是DB2的多种事务安全级别,在查询时,不需要关注更新和插入。因此需要查询支持脏读。每条查询的sql语句后面都要增加with ur选项。

在网上找了很久,很多人在问,但是没有结果。最后,在google找到解决办法,使用hibernate拦截器,进行拦截。下面是代码:

  1. import org.hibernate.EmptyInterceptor;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. /**
  5. * hibernate配置DB2时,为了防止高事务安全级别对查询造成影响,因此查询需要单独制定with ur。
  6. * 此类是hibernate拦截器,用于给select的查询末尾增加with ur选项,以防止查询时锁住数据库库。
  7. * @author superxb
  8. *
  9. */
  10. public class DB2Interceptor extends EmptyInterceptor {
  11. private static final long serialVersionUID = 1L;
  12. private static final Logger logger = LoggerFactory
  13. .getLogger(DB2Interceptor.class);
  14. @Override
  15. public String onPrepareStatement(String str) {
  16. // sql字符串全部转换成小写
  17. String compstr = str.toLowerCase();
  18. // 所有的select语句,只要是不包含with ur的。在后面都加上with ur
  19. if (compstr.matches("^select.*") && !compstr.matches(".*for update.*")) {
  20. if (!compstr.matches(".*with ur.*")) {
  21. str += " with ur ";
  22. logger.debug("Appending \"WITH UR\" to query.");
  23. }
  24. }
  25. return str;
  26. }
  27. }

拦截器创建好后,配置在hibernate的sessionFactory即可。配置参考如下:

  1. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  2. <property name="dataSource">
  3. <ref local="dataSource">
  4. </ref></property>
  5. <!-- 专门针对DB2增加的拦截器,在所有的sql后面增加 whit ur控制事务级别 -->
  6. <property name="entityInterceptor">
  7. <bean class="interceptor.DB2Interceptor">
  8. </bean></property>
  9. ……
  10. ……</bean>
如上配置之后。默认的,只要是select开头的sql语句,其中未包含with ur的话,就会在末尾增加with ur,以确保事务安全级别,实现hibernate映射DB2数据库时,能够进行脏读操作。

人气教程排行