Making a defensive copy of a JPA object

In my Spring application, I have code that reads into XML, then retrieves, for example, an organization entity via JPA, and then updates the fields found in XML in the Organization and returns the Organization.

But with code like this:

Organization updated = mergeToOrganization(jaxbOrganizationPojo, originalOrganization);

      

I really feel like I should start the method mergeToOrganization

by making a defensive copy originalOrganization

instead of directly modifying it. Direct mutation leaves me feeling dirty. But the alternatives to this seem to be a sketchy reflection or loooong get / set codebook.

Ideas? Opinions?

+3


source to share


2 answers


I don't see what the direct mutation problem is as long as you handle transactions properly. But if you want to remove an object from persistent context if you are using JPA 2.0 you can use EntityManager.detach () . This way, technically, an entity will never be marked as "dirty" and you don't need to feel bad. Also, remember to use merge()

instead of persist()

, or you will get a lot of nasty exceptions.



EDIT . If you want to return a fresh copy of your entity, the most likely cloning method I've seen so far is using ObjectOutputStream: http://javatechniques.com/blog/faster-deep-copies-of-java-objects/

+9


source


Another option is to use your own clone () method, or if you are using EclipseLink the copy () API can be used.



See, http://wiki.eclipse.org/EclipseLink/Examples/JPA/AttributeGroup#Copy_Examples

+1


source







All Articles