简体   繁体   English

@ManyToOne和@OneToOne在同一实体上

[英]@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). 如您所见,我在Address类的User实体顶部有两个注释(@ManyToOne和@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". 在这种情况下,您可以做的是标记“ 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;

   ...
}

只需在Address类中创建一个boolean isPrimaryAddress字段

Adding a flag in the library class is not a good solution. 在库类中添加标志不是一个好的解决方案。 It's a very bad proposition. 这是一个非常糟糕的主张。 All Users rely on one library class Address. 所有用户都依赖一个库类地址。 And all of them have (or may have) different 'primary address'. 他们都有(或可能有)不同的“主要地址”。 So, you need to create a relation structure (table) or a field in User class. 因此,您需要在User类中创建一个关系结构(表)或一个字段。 I think your initial variant is better, just use in @OneToOne option 'mappedBy' which relies on the User's field (for example, 'primaryAddress' - a reference to Address(bookId)). 我认为您的初始变体更好,只需在依赖于用户字段的@OneToOne选项'mappedBy'中使用(例如,'primaryAddress'-对Address(bookId)的引用)。

Addition: if you use an annotation @OneToOne (and other too) it's not necessary to have two-direction relation, you can have @OneToOne in User class but do not have it in Address class, usually it does not have any sense. 另外:如果使用注释@OneToOne(以及其他注释),则不必具有双向关系,可以在User类中使用@OneToOne,但在Address类中不要使用@OneToOne,通常它没有任何意义。

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

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