考虑下面给出的案例。
class Person{
@Id
String name;
@OneToMany
List<Address> addresses;
}
假设在一个会话中我创建一个人和一个地址值并保存,并在一个不同的会话中我做一个加载,当我坚持我将添加一些地址,我不希望保存的第一个地址被删除然后什么我该怎么办?
示例:
Session session1 = sf.getCurrentSession();
session1.save(person);//person here has an address diff from below
session1.close();
Session session2 = sf.getCurrentSession();
Person p1=session2.load(person,"Name");
List persA=new Arraylist<Address>();persA.add(new Address(...));
p1.setAddress(persA);
session.merge(p1);
session2.close();//this code is not exact I want to just project concept from here
所以我希望两个地址都保留在数据库中,当我急切地通过spring数据加载时,我应该得到两个地址!我怎么能得到这种行为?
全部谢谢!
答案 0 :(得分:0)
您正在通过创建新地址列表来覆盖地址列表。加载Person
后,请执行以下操作:
List persA = p1.getAdress(); //get the existing address associated to the person.
persA.add(new Address()); //add new address to the existing list.