【问题标题】:How to update the instances of mapped entity classes using hibernate session methods?如何使用休眠会话方法更新映射实体类的实例?
【发布时间】:2012-12-16 20:48:37
【问题描述】:

我需要更新bp 的两个字段“from”和“to”。 p 也与bp 一起被获取。自动刷新被禁用,所以我必须明确地进行刷新。

        Query q = session
                .createQuery(" select distinct bp from BP bp "
                        + " join fetch bp.p "
                        + " where bp.id = 2");

        bp = (BP) q.list().get(0);
        session.getTransaction().commit();

        session = test.services.HibernateUtil
                .getSessionFactory().getCurrentSession();
        session.beginTransaction();
        bp.setFrom(new Date());
        bp.setTo(new Date());
        session.update(bp);
        session.flush();
        session.getTransaction().commit();

当我运行上面的代码时,它显示以下异常:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: model.P

我无法在刷新之前保存p,因为save() 方法试图插入违反unique key constraint 的新记录。

当我尝试在刷新之前更新 p 时,出现以下异常:

java.lang.NullPointerException
    at org.hibernate.type.LongType.next(LongType.java:79)
    at org.hibernate.engine.Versioning.increment(Versioning.java:131)

有没有办法让p的状态持久化?

【问题讨论】:

  • 该对象的version 列是否为空?
  • 是 p 的版本字段为空。但 bp 不为空。谢谢
  • Hibernate 认为 p 是 transint(即数据库中不存在),因为它的版本字段为空。在数据库中设置为0,然后重新运行代码。

标签: java hibernate transient


【解决方案1】:

您能否在刷新会话之前尝试事务提交。

它应该可以工作。

【讨论】:

  • 我犯了一个错误(正如@Augusto 指出的那样),p 的版本字段为空,因此 p 没有得到更新。
猜你喜欢
  • 2020-02-16
  • 1970-01-01
  • 2015-10-31
  • 2019-12-03
  • 2020-12-18
  • 2016-12-20
  • 2016-10-18
  • 2016-02-14
  • 1970-01-01
相关资源
最近更新 更多