首页 文章

Hibernate merge()与版本控制

提问于
浏览
0

我正在使用hibernate 3.6,XML格式的映射 .

从以下架构开始 .

public class Card {
  @IndexedEmbedded
  private CardType cardType;

  private User user;//many-to-one
  ...
}

public class User {
  ...
  private int version;//Need to be strict about version on this table
  private Set<Card> cards = new HashSet<Card>();//cascade="all-delete-orphan"
  ...
}

如果我执行以下操作:
1:加载现有用户
2:关闭会话,在分离状态客户端工作 . 添加瞬态标签 .
3:将用户返回到服务器,openSession(),beginTransaction(),saveOrUpdate(user),commit() .

我收到以下错误“在Hibernate搜索中进行索引时出错(在事务完成之前)”...引起:org.hibernate.LazyInitializationException:无法初始化代理 - 没有会话

到目前为止,这对我来说很有意义 . CardType和Card需要更新其索引 . 所以我希望在saveOrUpdate()之前将我的第3步更改为merge() .

如果我这样做,它会将分离的所有属性(包括版本)复制到会话感知对象中 . 这当然意味着我的乐观锁定策略失败 - 没有警告版本问题 .

在这种情况下应该采取什么策略?

--Post更新以显示一些会话处理代码 -

public synchronized static SessionFactory getSessionFactory() {
  if (sessionFactory == null) {
    final AuditLogInterceptor interceptor = new AuditLogInterceptor();
    Configuration configuration = new Configuration();
    configuration = configuration.configure("hibernate.cfg.xml");
    configuration.setInterceptor(interceptor);
    sessionFactory = configuration.buildSessionFactory();
    AbstractSessionAwareConstraintValidator.setSessionFactory(sessionFactory);
  }
  return sessionFactory;
}

测试代码是这样的

sessionFactory = HibernateUtil.getSessionFactory();
sessionFactory.getCurrentSession().beginTransaction();
//Find user here
sessionFactory.getCurrentSession().getTransaction().commit();
sessionFactory.getCurrentSession().close();
//Edit User, add tags out of session. (not using OSIV)
sessionFactory.getCurrentSession().beginTransaction();
user = sessionFactory.getCurrentSession().merge();//Only works if I do this
sessionFactory.getCurrentSession().saveOrUpdate(entity);
sessionFactory.getCurrentSession().getTransaction().commit();
sessionFactory.getCurrentSession().close();

据我所知,我的hibernate.cfg.xml中没有“非标准”,只是列出了案例1线程org.hibernate.cache.NoCacheProvider中的这3行 .

我希望有足够的代码来演示会话使用情况 . 发布这个,我想知道拦截器是否可能会影响会话管理?

1 回答

  • 0

    你如何处理 Session ?在索引期间,Session仍然必须打开,以便索引器可以加载延迟加载的关联 . 在webapps中,Open Session In View模式通常用于在整个请求期间打开一个Session . 您需要发布一些更具体的代码才能获得更具体的反馈 . 另一种方法是急切加载关联(可能不是一个好主意) .

相关问题