我正在创建一个具有以下jpa实体(表)的项目
。。。依此类推
我很困惑在这里选择最佳设计/方法,即OneToOne双向或OneToOne单向?
我的第一个是OneToOne单向的,因为用户实体在应用程序中大量使用(诸如登录之类的操作),因此我不想在获取用户对象时获取其他实体。
下面是我的实体代码
USER:
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long userId;
@Column(nullable = false)
String firstName;
@Column(nullable = false)
String lastName;
@Column(nullable = false,unique=true)
String email;
// getter setters
}
UserPersonalDetails
@Entity
@Table
public class UserPersonalDetails {
@Id
Long userId;
@PrimaryKeyJoinColumn
@OneToOne(cascade = CascadeType.ALL)
@OnDelete(action = OnDeleteAction.CASCADE)
@MapsId
User user;
Long univercityId;
Long collageId;
String address;
String parentContact;
String tempAddress;
// getter setters
}
但是在这种方法中,当我尝试删除用户时,它失败,因为它在其他表上包含外键。
有人可以在这里建议理想的设计吗?
因此,作为一种选择,如果可能有一张桌子。考虑使用值类型而不是实体的情况。因此,您不必担心UserPersonalDetails的生命周期。它的寿命取决于具体的用户实例。
@Entity
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long userId;
@Column(nullable = false)
String firstName;
@Column(nullable = false)
String lastName;
@Column(nullable = false,unique=true)
String email;
UserPersonalDetails userDetails;
public UserPersonalDetails getUserDetails() {
return userDetails;
}
public void setUserDetails() {
this.userDetails = userDetails;
}
// other getter setters
}
@Embeddable
public class UserPersonalDetails {
@Column(nullable = false) // would be nested embeddable component
Long univercityId;
@Column(nullable = false) // would be nested embeddable component
Long collageId;
@Column(nullable = false)
String address;
@Column(nullable = false)
String parentContact;
@Column(nullable = false)
String tempAddress;
// getter setters
}