Hibernate - 通过更新父级创建子对象但需要生成子级的密钥

时间:2014-12-09 16:49:18

标签: java hibernate jpa

在我的工作中,我正在处理类似这样的代码......

父对象是User,子对象是Profile。我们创建Profile的方式是通过执行类似user.addProfile(profile)和service.update(user)的操作。所以我不是直接创建一个子对象,但由于它们有关系和级联,我相信这就是子对象的创建方式。

在这种情况下,我需要创建配置文件的密钥,更新Parent对象时是否可以这样做?

1 个答案:

答案 0 :(得分:1)

这是双向映射有帮助的时候。在Profile实体中创建User属性。而不是保存User实体保存Profile实体。

例如:

profile.setUser(user)
session.saveOrUpdate(profile)

profile.getkey()//this will have the key and it can be used immediately

<强>更新

Profile p = ... //somehow created this
User u = session.get(id,User.class);
u.addProfile(p);
session.saveOrUpdate(u);

p = getLastCreatedChild(u.getProfiles());  // based on the time it is created/ sorted by id you can get the last created child here
p.getKey();// will have the id


-------------User.java------------------

public class User {

   @OneToMany(cascade = CascadeType.ALL)
   private Set<Profile> profiles;
   ....
}
相关问题