Why merging is not cascaded on a one to many relationship

匆匆过客 提交于 2019-11-30 17:28:21

This is a standard problem with merge. Changes to child objects in the collection will get picked up.

The merge call can only cascade over objects that are in the list, so changes to objects not in the list get lost. Unfortunately, the oneToMany doesn't own the relationship: the child's ManyToOne does. So the child entities need to be merged for changes to be seen and pushed to the database. Child entities are independent objects and need to be merged individually when the are changed. That, or added to a different parent/tree to get merged.

Your question What could be the cause?. The cause is value content of parentNew. If the parentNew is one of the following cause, it will not effect/update to child.

  1. No reference instance parent and child vise visa. ---> It will throw exception.
  2. Parent parameter value have null or empty list of Clild --> This will be your cause.
  3. Child don't get updated name from UI.--> This will be your cause.

Example. I quick write it. It is OK.

Already exist data in DB

Parent                      Child
==================    =======================================
'P001', 'Parent 1'   'C002', 'Child 2', 'P001'
                     'C003', 'Child 3', 'P001'
                     'C001', 'Child 1', 'P001'

After Upldated:

Parent                      Child
==================          =======================================
'P001', 'Update Parent 1'   'C002', 'Update Child 2', 'P001'
                            'C003', 'Update Child 3', 'P001'
                            'C001', 'Update Child 1', 'P001'

List<Child> clidList = new ArrayList<Child>();
Parent parent = new Parent("P001", "Update Parent 1", clidList);
Child c1 = new Child("C001", "Update Child 1", parent);
Child c2 = new Child("C002", "Update Child 2", parent);
Child c3 = new Child("C003", "Update Child 3", parent);
clidList.add(c1);
clidList.add(c2);
clidList.add(c3);

Parent existingParent = em.find(Parent.class, parent.getId());
existingParent.setName(parent.getName());
existingParent.setChildren(parent.getChildren());
em.merge(existingParent);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!