OneToMany 更新在子类中不起作用
我在 Person 和 Role 类之间有 OnetoMany 关系。一个人可以有多个角色。当我创建新人员时,角色(现有记录)应使用人员 ID 进行更新。我正在使用 @OneToMany 映射与 CascadeType All,但 Role 类未使用 Person id 进行更新。如果在创建人员时创建了一个新角色并将其设置为关系,则可以正常工作。但是,当您创建新人员并尝试将其设置为现有角色时,它不会更新。
I have OnetoMany relationship between Person and Role class. A Person can have multiple roles. When I create a new person, roles (existing records) should get updated with the person ids. I am using @OneToMany mapping with CascadeType All, but the Role class is not getting updated with 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于双向链接,必须手动完成此操作。 hibernate教程提供了一个很好的例子: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#tutorial-associations-usingbidir
在您的情况下:在 OneToMany 方面,使您的 setPersons(... ) 方法受保护,并定义一个公共 addPerson(Person p) 方法,如下所示:
顺便说一句,如果一个人可以有多个角色,并且一个角色可以分配给多个人,那么很可能您真正想要的是多对多关系。所以你会:
在 Person 类中:
这是必要的,因为与 EJB 2.x 容器管理关系 (CMR) 相比,这不会自动处理。 Hibernate 使用 POJO 方法。 CMR 的缺点是,它需要一个容器来创建对象,而您可以在任何地方创建 POJO 对象。如果您创建它们,它们只是普通的旧 Java 对象,没有任何技巧。
这是一篇不错的博客文章,进一步讨论了这一点:http ://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bi Direction-assocations/
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
In your case: On the OneToMany side, make your setPersons(...) method protected, and define a public addPerson(Person p) method like 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. So you'd have:
And in class Person:
This is necessary, because in contrast to EJB 2.x Container Managed Relationships (CMR), this isn't handled automatically. Hibernate uses a POJO approach. The disadvantage of CMR is, that it requires a container to create the objects, whereas you can create POJO objects everywhere. And if you create them, they're just Plain Old Java Objects, no tricks.
Here's a nice blog article, which discusses this further: http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/