[英]Spring JPA Multiple Many-To-One Relationships in One Entity
I'm trying to create an entity, User who has two Addresses, a home address and a work address. 我正在尝试创建一个实体,该用户具有两个地址,一个家庭住址和一个工作地址。
Instead of storing the address info directly in the User class, I want to normalize it and store all addresses in one table and then link them to the user. 我不想将地址信息直接存储在User类中,而是要对其进行规范化并将所有地址存储在一个表中,然后将它们链接到用户。 Like so:
像这样:
@Entity
public class User {
@Id
private Integer id;
private Address homeAddress;
private Address workAddress;
// getters and setters
}
@Entity
public class Address {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private Integer id;
private String streetNumberAndName;
private String apartmentOrSuiteNumber;
private String city;
private String state;
private String zipcode;
// getters and setters
}
How do I do this using Spring JPA? 如何使用Spring JPA做到这一点? I understand this is a ManyToOne relationship but I'm not sure how to map two ManyToOne relationships to one entity.
我了解这是一个ManyToOne关系,但是我不确定如何将两个ManyToOne关系映射到一个实体。 Is this even possible?
这有可能吗?
Any help much appreciated. 任何帮助,不胜感激。
Thanks! 谢谢!
That's really simple. 那真的很简单。 Just map your User class like:
只需将您的User类映射为:
@Entity
public class User {
@Id
private Integer id;
@ManyToOne
@JoinColumn(name = "fk_home_address")
private Address homeAddress;
@ManyToOne
@JoinColumn(name = "fk_work_address")
private Address workAddress;
// getters and setters
}
The table structure would be like this: 表结构将如下所示:
user(id, fk_home_address, fk_work_address)
Note that this is a unidirectional relationship. 请注意,这是单向关系。
The best place to look for examples if you want to learn more is here . 如果您想了解更多信息,最好的例子是在这里 。 If you're looking for a bidirectional relation, learn here .
如果您正在寻找双向关系,请在此处学习。
private Integer id;
private Address homeAddress;
private Address workAddress;
with first situation, your structure table will be 在第一种情况下,您的结构表将是
user(id,home_address_id,work_address_id)
You might consider about second structure 您可能会考虑第二种结构
private Integer id;
private List<Address> userddress;//using one to many
your table structure will be 您的表结构将是
address(id,user_id)
It depend how do you want to organize the structure. 这取决于您要如何组织结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.