假设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)
应该添加孩子,但不覆盖。
注意
问题是关于在由doa加载,但是在保存到数据库之前将子代码添加到parent
之后,将其添加到Java代码之外(或者可能在其他线程中)的情况。
答案 0 :(得分:0)
我想它应该是Collection<Children> children
,而您的代码parent.setChildren(myNewCreatedChildren)
应该替换为parent.getChildren().addAll(children)
;
但根据我的经验,根本不容易处理@ManyToOne(mappedBy="parent")
和获取政策会更容易,提供childrenDao.fetchChildrensOfParent(parent)
和childrenDao.storeChildren(parent, children)
方法并仅使用这些方法要容易得多当需要时,使用这样的结构更容易将缓存添加到应用程序并更好地控制其填充和驱逐。