我有以下问题。我有 3 个实体,我正在使用 OneToOne 单向:
实体1
@Entity
public class Entity1 implements Serializable{
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
Long id;
String name;
String value;
}
实体2
@Entity
public class Entity2 implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@OneToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
Entity1 entity1;
public Entity1 getEntity1() {
return entity1;
}
String name;
String value;
}
实体3
@Entity
public class Entity3 implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;
@OneToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
private Entity1 entity1;
public Entity1 getEntity1() {
return entity1;
}
public void setEntity1(Entity1 entity1) {
this.entity1 = entity1;
}
String name;
String value;
}
一个小测试:
public void testApp()
{
EntityManager em = TestHibernateUtil.getEntityManager();
em.getTransaction().begin();
Entity1 entity1 = new Entity1();
entity1.name = "Name1";
entity1.value = "Value1";
Entity2 entity2 = new Entity2();
entity2.name = "Name2";
entity2.value = "Value2";
entity2.setEntity1(entity1);
**em.merge(entity2);**// if change that to persist - I get one Entity1
Entity3 entity3 = new Entity3();
entity3.name = "Name3";
entity3.value = "Value3";
entity3.setEntity1(entity1);
**em.merge(entity3);** // if change that to persist - I get one Entity1
em.getTransaction().commit();
}
因此,查看上面的测试,如果我em.merge
在事务提交后确实在持久性上下文中获得了 Entity1 的 2 个实体,如果我将其更改为,em.persist
那么我在持久性上下文中获得了 Entity1 的一个实体。谁能解释我为什么会发生这种情况或指向一些文档?