假设我们有这两个实体:
@Entity
class Address{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long bookId;
@ManyToOne
@OneToOne
private User user;
...
}
@Entity
class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Address> addresses;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private Address principalAddress;
...
}
如您所见,我在 Address 类中的用户实体顶部有两个注释(@ManyToOne 和@OneToOne)。关键是,我知道这是错误的,但我不知道如何正确映射它。设计有问题吗?逻辑是用户有一个地址列表和一个且唯一的主要地址。我怎样才能正确映射它?有什么想法吗?
最佳答案
在这种情况下,您可以做的是标记“isPrincipalAddress”。
@Entity
class Address{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long bookId;
private Boolean isPrincipalAddress;
@ManyToOne
private User user;
...
}
@Entity
class User{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<Address> addresses;
...
}
关于java - @ManyToOne 和@OneToOne 在同一实体上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59048617/