Using JPA i have a question relating to the CascadeTypes.
for Example:
@ManyToMany(fetch=FetchType.LAZY, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
is different to this:
@ManyToMany(fetch=FetchType.LAZY, cascade={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
Why? I need the cascadetype persist to automatically insert referenced objects in my entityclass. and i need merge because i dont want to have double entries in my tables. but when i define persist first, merging doesnt work, when i define merge first, persist doesnt work.
why?
The JPA specification is actually a very readable document and can be downloaded here:
https://jcp.org/aboutJava/communityprocess/final/jsr317/index.html
Inside it on page 384 it covers the cascade
attribute of the ManyToMany
annotation:
The cascade element specifies the set of cascadable operations that are propagated to the associated entity. The operations that are cascadable are defined by the CascadeType enum: public enum CascadeType { ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH}; The value cascade=ALL is equivalent to cascade={PERSIST, MERGE, REMOVE, REFRESH, DETACH}.
As you can see it says nothing about the order. What is probably happening is your application is sometimes using a new object that needs to be persisted and sometimes loading one from the database that then needs to be merged. In order words, its an application issue.
Personally I use a DIY approach to merging entities in my persistence context. A good article to read on the subject is here:
http://blog.xebia.com/2009/03/23/jpa-implementation-patterns-saving-detached-entities/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With