我有以下模型-具有用户个人资料的用户实体。根据用户的角色,用户配置文件会有所不同。我已尝试根据此link使用共享主键在用户和用户配置文件之间建立这种一对一的映射关系
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(updatable = false,nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long userId;
private String role;
@OneToOne
@PrimaryKeyJoinColumn
private UserProfile profile;
}
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class UserProfile implements Serializable {
@Id
@Column(unique = true,nullable = false)
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen",strategy = "foreign",
parameters = @Parameter(name = "property",value = "user"))
private Long userId;
@OneToOne(mappedBy = "profile")
private User user;
}
@Entity
public class DeviceUserProfile extends UserProfile {
private Long deviceId;
}
@Entity
public class AdminUserProfile extends UserProfile {
private String firstName;
private String lastName;
}
但是,当我插入用户实体时,用户配置文件没有被添加到相应的表中。
User user1 = new User();
user1.setRole("Device");
DeviceUserProfile deviceUserProfile = new DeviceUserProfile();
deviceUserProfile.setDeviceId(1234L);
user1.setProfile(deviceUserProfile);
deviceUserProfile.setUser(user1);
session.beginTransaction();
session.save(user1);
session.getTransaction().commit();
关于如何解决此问题或我的模型是否更好的任何指示将非常有帮助。
最佳答案
我在cascade = CascadeType.ALL
和User.profile
处添加UserProfile.user
如下
@Entity
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(updatable = false,nullable = false)
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long userId;
private String role;
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private UserProfile profile;
}
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class UserProfile implements Serializable {
@Id
@Column(unique = true,nullable = false)
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen",strategy = "foreign",
parameters = @Parameter(name = "property",value = "user"))
private Long userId;
@OneToOne(mappedBy = "profile",cascade = CascadeType.ALL)
private User user;
}