hibernate查询出的数据和数据库不一致
之前直接使用hibernate的时候就出现过已经进行物理存储后的数据,查询不出来的情况,既然是已经存储后的数据,说明事务已经提交,想必问题出在查询时,查询的缓存,没有查询数据库。时有时无就很奇怪。
现在做项目使用spring的hibernateTemplate
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml">
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="springDataManager" class="com.jason.base.util.SpringDataManager">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
但是偶尔还是会出现已经保存的数据查询不出来,或者时有时无的情况。
首先尝试清空缓存
1,hibernateTemplate.clear();没有效果
2,hibernateTemplate.evict(Peg.class);这个方法最后会调用session.evict(entity);
public void evict(final Object entity)
throws DataAccessException
{
executeWithNativeSession(new HibernateCallback() {
public Object doInHibernate(Session session)
throws HibernateException
{
session.evict(entity);
return null;
}
final HibernateTemplate this$0;
private final Object val$entity;
{
this$0 = HibernateTemplate.this;
entity = obj;
super();
}
}
);
}
但是还是没有用,该方法只能是从session中将对象移除,也就是说入参是对象,不是class。
3,查看hibernateTemplate源代码,发现这么一段
if(isAlwaysUseNewSession())
SessionFactoryUtils.closeSession(session);
else
SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
也就是说执行完数据库操作后是否关闭session是根据一个参数判断的
public HibernateTemplate()
{
allowCreate = true;
alwaysUseNewSession = false;
exposeNativeSession = false;
checkWriteOperations = true;
cacheQueries = false;
fetchSize = 0;
maxResults = 0;
}
这里默认设置的是不必每次都新建一个session,这样分析有可能两次操作使用的是同一个session,而session中的缓存数据没有刷新,所以存在查询脏读的问题。
而可能每次去到的session不一样,时有时无的情况出现了。
试着修改这个参数为true
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
hibernateTemplate.setAlwaysUseNewSession(true);
this.hibernateTemplate = hibernateTemplate;
}
这样spring初始化的时候容器里的hibernateTemplate实例对象就有了一个为true的参数,每次都会关闭session,重新获取一个session。
改变后暂时没有发现问题出现了,但这个问题很奇怪,是偶尔冒出来的,暂时先这样,继续观察,实在搞不定就只能换掉hibernate了。
转自:https://www.cnblogs.com/yangchengInfo/p/3585264.html

浙公网安备 33010602011771号