首页 > 解决方案 > @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?

标签: javaspringhibernatejpa

解决方案


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;

   ...
}

推荐阅读