欢迎投稿

今日深度:

DB2使用Hibernate拦截器实现脏读(with ur),db2hib

DB2使用Hibernate拦截器实现脏读(with ur),db2hibernate


工作需要,最近要让开发的系统底层适应的数据库增加对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即可。配置参考如下:

	<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数据库时,能够进行脏读操作。


Java通过jdbc连接DB2可以使用with as( select

session.createQuery()里边要写hql。

你写那句是个sql,不好使。
session.createSQLQuery(),可以执行sql。

但你用hibernate了,还是考虑hql实现吧,你那个查询又不是多复杂。

我也没看明白你为啥要用子查询。
 

hibernate中 flush方法的运用

你把session.beginTransaction() ;
这个注释掉试试,你用了事务,没有提交,数据库是没有数据,应该是可以理解的
 

www.htsjk.Com true http://www.htsjk.com/shujukunews/3474.html NewsArticle DB2使用Hibernate拦截器实现脏读(with ur),db2hibernate 工作需要,最近要让开发的系统底层适应的数据库增加对DB2的支持,虽然使用了DB2,但是就性能考虑,和业务需要。查询不需要进行...
评论暂时关闭