我有两个@OneToOne关系的实体:
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_user")
private Long id;
@OneToOne(cascade = CascadeType.MERGE, orphanRemoval=true)
@JoinColumn(name = "id_details")
private UserDetails details;
//...username, password, email
}
@Entity
public class UserDetails implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_user_details")
private Long id;
//...firstname, lastname, address
}
首先,我使用UserDetails保存用户:
public class Main {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
UserDetails details = new UserDetails("John", "Doe", "NYC 11");
User user = new User("uname", "pass", "mail", details);
em.merge(user);
em.getTransaction().commit();
em.close();
emf.close();
}
}
一切正常,因为有级联MERGE,因此两个实体都被保存。当我运行另一个班级时:
public class MainUpdate {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu");
EntityManager em = emf.createEntityManager();
User user = em.find(User.class, 1L);
user.setDetails(null);
em.getTransaction().begin();
em.merge(user);
em.getTransaction().commit();
em.close();
emf.close();
}
}
我预计用户中的id_details将在数据库中设置为null(它是)但是因为有orphanRemoval = true我还希望孤儿行将从userdetails表中删除但不是。
当我设置CascadeType PERSIST而不是MERGE时,有趣的是删除了孤儿。有人可以解释为什么PERSIST与orphanRemoval一起工作但是MERGE没有吗?
GitHub回购:https://github.com/slwch/onetoone-orphan
使用Hibernate 5.0.6和4.1.8进行测试