简体   繁体   中英

@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;

   ...
}

只需在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. 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)).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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