java JPA - 更新 OneToMany-Relations 中的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17137903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA - updating objects in OneToMany-Relations
提问by Cyboot
Well I am a little confused because I just can't find any solution on my problem (maybe some kind of a blackout)
好吧,我有点困惑,因为我找不到任何解决我的问题的方法(也许是某种停电)
Lets say I have the following (simplified) Entities:
假设我有以下(简化的)实体:
@Entity
public class Employee {
@Id
private long id;
@OneToMany(mappedBy="owner")
private Collection<Phone> phones;
}
@Entity
public class Phone {
@Id
private long id;
@ManyToOne
private Employee owner;
}
and I have a phoneobject managed by JPA. And now i want to change the Employee of that phoneobject with something like that:
我有一个由 JPA 管理的电话对象。现在我想用这样的东西来改变那个电话对象的员工:
phone.setEmployee(otherEmployee);
I thought that JPA would update the corresponding Employee would be updated too. Am I wrong? I experimented with the annotations @ManyToOne and @OneToMany (cascade = CascadeType.ALL, orphanRemoval = true) but it doesn't work.
我认为 JPA 会更新相应的 Employee 也会更新。我错了吗?我尝试了注释@ManyToOne 和@OneToMany(cascade = CascadeType.ALL,orphanRemoval = true)但它不起作用。
Do I have to update the Employee object myself? Unfortunatly I didn't find that case in any tutorial or other example, so I hope you can tell me more, I am confused. Thanks in advance.
我必须自己更新 Employee 对象吗?不幸的是,我在任何教程或其他示例中都没有找到这种情况,所以我希望你能告诉我更多,我很困惑。提前致谢。
Editto make it even clearer:
编辑以使其更清晰:
Phone phone = new Phone();
Employee employee = new Employee();
phone.setEmployee(employee);
em.persist(employee);
em.persist(phone);
employee.getPhones(); //the phone object should be included here.