我有两个实体类 A 和 B,如下所示。
public class A{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy = "a", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
private List<B> blist = new ArrayList<B>();
//Other class members;
}
B类:
public class B{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
private A a;
//Other class members;
}
我有一个将 B 对象添加到 A 对象的方法。我想返回新添加的 B 对象的 id。
例如:
public Long addBtoA(long aID){
EntityTransaction tx = myDAO.getEntityManagerTransaction();
tx.begin();
A aObject = myDAO.load(aID);
tx.commit();
B bObject = new B();
bObject.addB(bObject);
tx.begin();
myDAO.save(aObject);
tx.commit();
//Here I want to return the ID of the saved bObject.
// After saving aObject it's list of B objects has the newly added bObject with it's id.
// What is the best way to get its id?
}