What is the best way to safely update a sleep object?

First we explain the context. I have a backend Java (Spring / Hibernate) application accessed through JMS. I have a client application (RESTfull) that I access through Url. I have a complex entity with more than one list (most of them are lazy), and this object is a composition of other objects.

Problem. Since I access it through the URL, I create the Java object in the client application from the URL parameters. I send it to the server via JMS, but on the backEnd I do not have a Hibernate object, so I cannot merge it.

I can go through everything that came from the client, for example:

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

and repeat it for each composition object, but I wonder if there is a more elegant and "easy to maintain" way to update this object with all the changes.

Hope I explained it well. Thanks in advance!

+6
source share
2 answers

From your description, it seems that the steps you are following are correct. The first (get the object) and the last (update the object) steps are inevitable. The only place you can optimize is part of the validation / configuration. To do this, you can write a generic method that takes two objects and compares them for changes using Reflection. Thus, it can be reused again.

Here is an example code using reflection. Change it according to your needs

+2
source

If you are sure that you had the latest values ​​for the changed fields of the object (for example, by saving the version field with optimistic locking) and / or you intend to simply overwrite all the changed fields, there is no need to check whether the fields are changed or not. Just find the objects and set the fields that you have (including the ID and version), and Hibernate will overwrite your changes, if any, into the database, unless the object has been modified by any other thread. In this case, the update / merge fails due to the exclusion of optimistic blocking.

So the steps are:

  • Find Hibernate object by id
  • Set new / changed values, including version
  • Update / Merge / Saved

Of course, you need to make sure that you have the correct cascades in your entities or update objects, one for each related one.

0
source

All Articles