Forcing a method to be non-transactional in JPA (Eclipselink)
I am developing an application using Eclipselink and as part of the app I need to be able to manipulate some of the objects which involves changing data without it being persisted to the database (i merging/changing objects for some batch generation processes).
I am reluctant to change the data in the Entity objects, as there is a risk that even though i have not marked the methods as @Transactional
, this method could in the future be inadvertantly called from within a transactional method and these changes could be persisted.
So my question is, is there anyway to get around this? Such as force a method to always be non-transactional regardless; terminate any transactionality as soon as the method is started; etc.
I know there is a .detach() method that can detach the objects from the Entity Manager, however, there are many objects and this seems开发者_运维技巧 like a potentially error prone fail-safe on my code.
If this is spring, you have
@Transactional(propagation=Propagation.NOT_SUPPORTED)
Execute non-transactionally, suspend the current transaction if one exists. Analogous to EJB transaction attribute of the same name.
If it's EJB, you have a transaction attribute of the same name.
Anyway, instead of playing around with transactions, you can simply clone your object and modify the required data. Deep cloning can be achieved via commons-lang SerializationUtils
.
I'm not sure to understand your use case but I wouldn't mess with transaction here and either:
- Not
merge
changes made to entities ~or~ refresh
any changes made to entities before amerge
(but why would you callmerge
?) ~or~- Work on non-managed copies of entities ~or~
Declare some classes are Read-Only (EclipseLink specific, see Declaring Read-Only Classes and How to Use the @ReadOnly Annotation). From the doc:
Any changes made within a managed instance in a transaction or to a detached instance and merged will have no effect in the context of a read-only entity class.
精彩评论