我有班级用户和班级地址。 地址仅包含4个属性:
publiс class Address {
private Long id;
private String country;
private String city;
private String street;
// getters and setters
}
用户的结构:
public class User {
private Long id;
private String name;
private Address homeAddress;
private Address businessAddress;
// other fields and methods
}
当一个实体(用户)有两个时,选择哪种类型的JPA关系以及如何通过注释进行注释(或更多)具有某种自定义类型的字段(地址)?
如果用户只有一个地址,那将是一对多的关系。但是这个案子怎么样?如何在我的系统中正确定义这些对象?
我尝试在Address类中创建另一个字段users
:
@OneToMany(mappedBy = "?")
private List<User> users;
但这不是我问题的解决方案,因为User类中有两个Address类型字段。并且不清楚是否有必要在mappedBy
注释中定义...
我将不胜感激任何建议!
答案 0 :(得分:0)
public class User {
private Long id;
private String name;
private Address homeAddress;
private Address businessAddress;
// other fields and methods
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "HOME_ADDRESS_ID")
public Address getHomeAddress() {
return homeAddress;
}
public void sethOMEAddress(Address homeAddress) {
this.homeAddress= homeAddress;
}
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "BUSINESS_ADDRESS_ID")
public Address getBusinessAddress() {
return businessAddress;
}
public void setBusinessAddress(Address businessAddress) {
this.businessAddress= businessAddress;
}
}
并且类地址保持不变。