简体   繁体   English

OneToMany Update在子类中不起作用

[英]OneToMany Update not working in child class

I have OnetoMany relationship between Person and Role class. 我在Person和Role类之间存在OnetoMany关系。 A Person can have multiple roles. 一个人可以扮演多个角色。 When I create a new person, roles (existing records) should get updated with the person ids. 创建新人员时,应使用人员ID更新角色(现有记录)。 I am using @OneToMany mapping with CascadeType All, but the Role class is not getting updated with Person id. 我正在将@OneToMany映射与CascadeType All一起使用,但是Role类未使用Person ID更新。 If a new role is created and set as a relationship while creating the Person, it works fine. 如果在创建人员时创建了新角色并将其设置为关系,则可以正常工作。 But when you create a new Person and try to set it to existing Role it doesn't get updated. 但是,当您创建一个新的Person并将其设置为现有Role时,它不会更新。

This must be done manually for bidirectional links. 对于双向链接,必须手动完成此操作。 The hibernate tutorial provides a good example: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#tutorial-associations-usingbidir 休眠教程提供了一个很好的示例: http : //docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#tutorial-associations-usingbidir

In your case: On the OneToMany side, make your setPersons(...) method protected, and define a public addPerson(Person p) method like this: 在您的情况下:在OneToMany一侧,将setPersons(...)方法设置为受保护,并定义一个公共addPerson(Person p)方法,如下所示:

public void addPerson(Person p) {
    this.getPersons().add(p);
    p.setRole(this);
}

By the way, if a person can have multiple roles, and a role can be assigned to multiple persons, then most probably what you actually want is a ManyToMany relationship. 顺便说一句,如果一个人可以有多个角色,并且一个角色可以分配给多个人,那么您实际想要的最可能是ManyToMany关系。 So you'd have: 因此,您将拥有:

public void addPerson(Person p) {
    this.getPersons().add(p);
    p.getRoles().add(this);
}

And in class Person: 在课堂上的人:

public void addRole(Role r) {
    this.getRoles().add(r);
    r.getPersons().add(this);
}

This is necessary, because in contrast to EJB 2.x Container Managed Relationships (CMR), this isn't handled automatically. 这是必要的,因为与EJB 2.x容器托管关系(CMR)相比,它不是自动处理的。 Hibernate uses a POJO approach. Hibernate使用POJO方法。 The disadvantage of CMR is, that it requires a container to create the objects, whereas you can create POJO objects everywhere. CMR的缺点是,它需要一个容器来创建对象,而您可以在任何地方创建POJO对象。 And if you create them, they're just Plain Old Java Objects, no tricks. 而且,如果创建它们,它们只是普通的Java对象,没有技巧。

Here's a nice blog article, which discusses this further: http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/ 这是一篇不错的博客文章,进一步讨论了这一问题: http : //blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM