我正在尝试使用JPA / Hibernate设置以下表:
User: userid - PK name Validation: userid - PK, FK(user) code
可能有很多用户,每个用户最多只能有一个验证码,也可能没有。
这是我的课程:
public class User { @Id @Column(name = "userid") @GeneratedValue(strategy = GenerationType.IDENTITY) protected Long userId; @Column(name = "name", length = 50, unique = true, nullable = false) protected String name; ... } public class Validation { @Id @Column(name = "userid") protected Long userId; @OneToOne(cascade = CascadeType.ALL) @PrimaryKeyJoinColumn(name = "userid", referencedColumnName = "userid") protected User user; @Column(name = "code", length = 10, unique = true, nullable = false) protected String code; ... public void setUser(User user) { this.user = user; this.userId = user.getUserId(); } ... }
我创建一个用户,然后尝试使用以下代码添加验证代码:
public void addValidationCode(Long userId) { EntityManager em = createEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); // Fetch the user User user = retrieveUserByID(userId); Validation validation = new Validation(); validation.setUser(user); em.persist(validation); tx.commit(); } ... }
当我尝试运行它时,我收到org.hibernate.PersistentObjectException:分离的实体传递给持久化:用户
我还尝试在Validation类中使用以下代码:
public void setUserId(Long userId) { this.userId = userId; }
当我创建验证码时,我只是做:
Validation validation = new Validation(); validation.setUserId(userId); em.persist(validation); tx.commit();
但是,由于User为null,因此我得到org.hibernate.PropertyValueException:not- null属性引用了null或瞬态值:User.code
感谢您提供有关如何最好地解决此问题的帮助!
如果您使用hibernate模式,也可以使用
public class Validation { private Long validationId; private User user; @Id @GeneratedValue(generator="SharedPrimaryKeyGenerator") @GenericGenerator(name="SharedPrimaryKeyGenerator",strategy="foreign",parameters = @Parameter(name="property", value="user")) @Column(name = "VALIDATION_ID", unique = true, nullable = false) public Long getValidationId(){ return validationId; } @OneToOne @PrimaryKeyJoinColumn public User getUser() { return user; } }
Hibernate将确保Validation的ID与User实体集的ID相同。