How to cascade persist only new entities

試著忘記壹切 提交于 2019-12-04 09:26:28

The best way to think about cascades in hibernate is if you call the method X on the parent then it will call the method X on each of the children. So yes, if you call persist on the user then it will call persist on each of the children, regardless of whether they have been persisted or not.

This situation is not ideally handled with cascades. Cascade persist is intended for situations where all children are created with the parent (for example, if a use had a list of "skills") and more intended for one-to-many.

I would personally not use a cascade in this situation. Flagrant use of cascades when they are not needed can slow an application down.

If you feel you must use a cascade you can use a cascade merge. Merge will persist entities when they are not persisted already. However, merge has some very bizarre side effects which is probably why you didn't notice it working. Consider the following example:

x = new Foo();
y = new Foo();

em.persist(x);
Foo z = em.merge(y);

//x is associated with the persistence context
//y is NOT associated with the persistence context
//z is associated with the persistence context

Your issues is you are corrupting your persistence context. Managed objects should only reference other managed objects. So having your new object reference an existing detached object is wrong.

What you need to do is do a find() to get the managed version of the existing detached object and have your new object reference it, then call persist on it.

You could also use merge() instead of persist and it should resolve your object's references. Note that merge does not make a detached object managed, it return a copy of the detached object that is managed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!