java - @ManyToOne and @OneToOne on the same entity
问题描述
Let's say we have these two entities:
@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;
...
}
As you can see I have two annotation on top of User entity inside Address class (@ManyToOne and @OneToOne). The point is, I know it is wrong but I don't know how to map it right. Is there a design problem? The logic is that a User has a list of addresses and one and only principal address. How can I map it correctly? any idea?
解决方案
In situations like this what you can do is have flag "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;
...
}
推荐阅读
- c# - 使用 Dax 查询:'(' 的语法不正确
- wordpress - 如何在 Wordpress 网站页面上修复此 404 错误?
- kotlin - 在kotlin中获取空指针异常
- sql - Hive: java.lang.OutOfMemoryError: Java heap space and Job running in-process (local Hadoop)
- nginx - 使用 NGINX (Docker) 将 /api 请求重定向到端口 3000
- javascript - 使用 Watir 从 Angular 非传统下拉菜单中进行选择
- excel - 我们可以计算我们在编码经典asp中上传到网页上的工作簿中工作表的最后一行吗
- go-git - 如何解决提交到分支?
- angular - Angular 8 拒绝加载加载图像,因为它违反了以下内容安全策略指令
- nlp - 什么是 LUIS“语音请求”?