Hibernate:在事务提交和会话关闭之前调用已保存对象的getter

时间:2015-04-15 18:59:22

标签: java sql hibernate

我有2个Hibernate实体A和B:

public class A implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO )
  private Integer id;

  @OneToOne(mappedBy = "a")
  B b;

  // ctors, getters, setters
}

public class B implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO )
  private Integer id;

  @OneToOne
  @JoinColumn
  A a;  

  // ctors, getters, setters 
} 

当我创建并保存这些对象时,我会同时创建它们。创建它们之后,我想调用a.getB(),但这会返回null。如果我提交事务,打开一个新会话,并加载A,则a.getB()正确返回b。

这不起作用:

public void doSave() {
  Session session = getSessionFactoryFromSomewhere.openSession();
  session.beginTransaction();
  A a = new A();
  B b = new B();
  b.setA(a);
  session.save(a);
  session.save(b);

  A aFromDb = (A) session.load(A.class, a.getId());
  B bFromA = aFromDb.getB(); // bFromA is null in this case!
}

这确实有效:

public void doSave() {
  Session session = getSessionFactoryFromSomewhere().openSession();
  Transaction tx = session.beginTransaction();
  A a = new A();
  B b = new B();
  b.setA(a);
  session.save(a);
  session.save(b);

  tx.commit();
  session = getSessionFactoryFromSomewhere().openSession();
  tx = session.beginTransaction();

  A aFromDb = (A) session.load(A.class, a.getId());
  B bFromA = aFromDb.getB(); // bFromA is equal to b, which is correct.
}

如何在不提交事务,关闭会话和启动新会话+事务的情况下使a.getB()返回b?

2 个答案:

答案 0 :(得分:0)

在两个实体之间的one-to-one关联中,如果你想在不提交事务或关闭并重新打开会话的情况下从另一个实体获取每个对象,你需要向对方添加对象尝试这个:

 A a = new A();
 B b = new B();
 b.setA(a);
 a.setB(b);

答案 1 :(得分:0)

您只需在会话中保存实体之后但在再次查询数据库以查看更新的实体之前调用session.flush()