简体   繁体   中英

What is the best way to safely update hibernate entity?

First to explain the context. I have backend Java (Spring/Hibernate) application that I access via JMS. I have client app (RESTfull) that I access via Url. I have a complex entity with more than one list (most of it are lazy) and this entity is composition of xy other entities.

Problem: Since I access it via URL, I create Java object in client app from URL parameters. I'm sending it to backend via JMS, but on the backEnd, I do not have Hibernate object, so I cant simple merge it.

I can go trough all that came from client like:

  • get hibernate object by id
  • check what is different
  • set new values
  • update

and repeat it for every composition entity, but I'm wondering if there is more elegant and "easy to maintain" way to update this entity with all changes.

I hope I explained it well. Thanks in advance!

From your description it seem the steps you follow are right. The first(get object) and last(update object) steps are inevitable. The only place where you can optimize is the checking/setting part. For that you can write a generalized method which accepts two objects and compares them for changes using Reflection. This way it can be reused again.

Here is a sample code using reflection. Change it to suit your need

If you are confident that you have had the latest values for modified entity fields (eg by keeping an optimistic-lock version field) and/or you intend to just overwrite all of the modified fields, there is no need to check if the fields are changed or not. Just find the entities and set the fields that you have (including ID and version) and Hibernate will overwrite your changes, if any, to the database unless an entity has been modified by some other thread in the meantime. In this case, the update/merge fails by an optimistic lock exception.

So the steps would become:

  • Find Hibernate object by id
  • Set new/modified values including version
  • Update/merge/persist

Of course, you need to make sure you have proper cascades on your entity relationships or update entities one by one for every related one.

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