简体   繁体   English

如何正确使用一对多和多对一注释?

[英]How to use one-to-many and many-to-one annotations correctly?

Good day, 美好的一天,

I have started my first JPA project based on a CRM application and I have some difficulties with understanding the correct usage of ManyToOne and OneToMany annotations. 我已经开始了基于CRM应用程序的第一个JPA项目,并且在理解正确使用ManyToOne和OneToMany批注方面遇到一些困难。 For instance, let's say I have two classes; 例如,假设我有两个班级。 these will be Account and User classes: 这些将是“帐户”和“用户”类:

public class Account {

@OneToMany
private Set<User> userList = new HashSet<User>();

and

public class User {

@ManyToOne
private Account account;

How do I correctly annotate the many-to-one and one-to-many relationships? 如何正确注释多对一和一对多关系? I've tried reading the docs but still I could not retrieve a correct conclusion. 我已经尝试阅读文档,但是仍然无法获得正确的结论。

Thank for your attention 感谢您的关注

A 'canonical' OneToMany mapping for your case, meaning meaning bidirectional, with the foreign key in the table of the many-side (the owning side) would in your case look like this: 在您的情况下,针对您的情况的“规范” OneToMany映射(意味着双向)具有外键(在多方(拥有方)的表中):

public class Account {

@OneToMany(mappedBy="account")
private Set<User> userList = new HashSet<User>();

and

public class User {

@ManyToOne
private Account account;

The only difference to your existing code is the mappedBy attribute, to change two unidirectional relationships into a single, bidirectional relationship. 与现有代码的唯一区别是mappedBy属性,该属性将两个单向关系更改为单个双向关系。

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

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