简体   繁体   中英

JPA - update more fields on entity properly

I would like to do a simple update on a managed JPA entity on many fields. First I query the entity which I would like to update:

MyEntity managedEntity = entityManager.createQuery(query).getSingleResult();

Then I need to update this entity with a new "MyEntity" object which is not managed by JPA:

MyEntity notManagedEntity = new MyEntity();

Of course it would be possible to read each field from notManagedEntity and set them to managedEntity which would do the update.

But is there a more elagant way to update the managed entity without needing to get and set every field one by one?

AFAIK, it's not a good idea to change a reference to a managed entity, because the persistence context will still reference the old entity, so any flush would trigger an exception... It's even more important when working with complex entities holding collections or ManyToOne references.

A related topic: What is the best way to update the entity in JPA

I would suggest to read the question: Copy all values from fields in one class to another through reflection

This looks like the answer to your question. You then have to create a copy of the entiy you got from

MyEntity managedEntity = entityManager.createQuery(query).getSingleResult();

After you created the copy of you java object, you have to set the identifier from the entity an new value an inset this new Object to the persistent layer again.

From desinge perpective it looks a bit confusing, but if this is the request, at least from technical perspective it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM