In my Spring application, I have code that reads in XML, then fetches for example an Organization entity via JPA and then updates the fields found in the XML to the Organization and returns the Organization.
But with code like this:
Organization updated = mergeToOrganization(jaxbOrganizationPojo, originalOrganization);
I really feel like I should start the mergeToOrganization method by making a protective copy of originalOrganization instead of directly mutating it. Direct mutation leaves me feeling dirty. But alternatives to that seem to be sketchy reflection or loooong get/set boiler plate code.
Ideas? Opinions?
I don’t see what’s the problem with direct mutation as long as you handle transactions properly. But if you want to remove the entity from persistent context, assuming you’re using JPA 2.0, you can use EntityManager.detach(). This way, technically, the entity will never be marked “dirty” and you don’t have to feel bad about it. Also, make sure to use
merge()to save it back and notpersist(), or you’ll get many nasty exceptions.EDIT If you want to return a new copy of your entity, the most bullet-proof cloning method I’ve seen so far is to use ObjectOutputStream: http://javatechniques.com/blog/faster-deep-copies-of-java-objects/