Hibenate系列持久性

问题描述 投票:0回答:1

Hi all I am new to Hibernate, while going through hibernate documentation I came across this statement which states that "Two entities cannot share a reference to the same collection instance", but when I am using below code no error is coming everything is fine and hibernate persisting both entities and corresponding collection references in DB without any issue, am I missing something can this statement be explained and in which scenario it is applicable.

Entity1 :

public class Person {

@Id
@GeneratedValue
private Long id;

@CreationTimestamp
private LocalDateTime date;

@ElementCollection
private List<String> phones = new ArrayList<>();

@ElementCollection
private Set<LocalDateTime> personOrderDates;
}

Entity2 :

public class Home {

@Id
@GeneratedValue
private long id;


@ElementCollection
private List<String> homePhoneList;
}

Hibernate持久化代码。

    Person person1 = entityManager.find(Person.class, 48l);
    Person person2 = entityManager.find(Person.class, 49l);

    List<String> newPhoneList=new ArrayList();
    newPhoneList.add("x");
    newPhoneList.add("y");
    newPhoneList.add("z");

    person1.setPhones(newPhoneList);
    person2.setPhones(newPhoneList);

    Home home1=Home.builder().homePhoneList(newPhoneList).build();

    entityManager.persist(home1);
    entityManager.persist(person1);
    entityManager.persist(person2);

这里很明显,我们能够在同一个实体(Person)的两个实例之间共享相同的集合引用,也能够与完全不同的实体类型(Home)共享,没有任何问题。

java hibernate collections hibernate-mapping
1个回答
0
投票

两个实体不能共享对同一个集合实例的引用

这仍然是正确的。这意味着如果你加载其中一个实体并改变电话集合,另一个实体的电话集合保持不变。

你只是在你的java中共享了一个引用,而不是在数据库中。下一次,这个共享引用将消失,而你所有的实体都是由一个单独的引用组成的,他们自己的列表。

© www.soinside.com 2019 - 2024. All rights reserved.