2016-04-21 46 views
3

假设Parent已经存在id=1。它已经有2个孩子。如何使代码:如何将孩子添加到现有的父亲节点中进行休眠?

Parent parent = parentDao.getbyId(1); 
//here somebody added a collection of children 
parent.setChildren(myNewCreatedChildren) 
parentDao.save(parent); 

如何保存母公司获得parentDao.getbyId(1).getChildren()回报之后somebody children + myNewCreatedChildren?例如。打电话parentDao.save(parent)应该加儿童但不要覆盖。

注意

的问题是有关情况时chidren构成了Java代码之外添加(或可能是在其他线程)的parent它是由DOA加载之后,但在它保存到数据库中。

+1

http://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#_optimistic –

+0

不理解你,关于文档参考。是的,可以使用版本号或交易管理来表明我们是否有父母变更。但问题不在于此,而是在未加载的情况下将子项添加到已存在的集合中。你能否添加一些更多的解释? – Cherry

+0

AFAIK,向集合添加一个元素将被视为对父级的更改,版本将会增加,并且会检测到冲突。 –

回答

0

我想应该是Collection<Children> children,你的代码parent.setChildren(myNewCreatedChildren)应该用parent.getChildren().addAll(children)代替;

但是从我的经验,这是一个更容易一点不处理@ManyToOne(mappedBy="parent")和所有获取的政策,这是很容易提供childrenDao.fetchChildrensOfParent(parent)childrenDao.storeChildren(parent, children)方法,并与那些仅在需要时它的工作,这样的结构更容易将缓存添加到应用程序并更好地控制其人口和驱逐。