JPA: What is an efficient way to merge a single object?

Technologies: Spring, Hibernate, JSR-303, JQuery
Platform: Windows

I am trying to implement a simple update usage example. See Link to DAO / Service / Controller Source Code

Class2 contains many properties, including Class1. The Class2Controller uses Spring to create a new Class2 object and binds the parameters of the HttpRequest object to Class2. He then calls the service, which in turn calls the DAO. In the DAO, what is the most efficient way to update this new Class2 object to the database?

Option 1:

  • Currently in the DAO, I am retrieving a Class2 object from the database.

    Class2 class2Persisted = em.find(Class2.class, class2Request.getId());

  • Update the retrieved object with the properties of the request object and commit

     tx.begin(); class2Persisted.setClass1(class2Request.getClass1()); em.merge(class2Request); tx.commit(); 
  • Above, I only update one property using setClass1. But in Class2 there are many properties that will need to be updated. Is there any other efficient way to merge class2Persisted with class 2Request at the object level, and not at each property level?

Option 2

  • Let Class2Controller retrieve the class2Persisted object and request Spring to bind the parameters.

  • I realized that option 2 is not a viable option. See Another issue I encountered earlier. Hibernate will try to load related objects and will throw an EntityNotFoundException without my user restriction @IdMustExist to be able to check.

Please offer if you have other suggestions.

+4
source share
1 answer

You must use dynamic-update = true to update the entity / table and are highly optimized and will update columns whose value changes and does not include all fields.

You can use with annotations pojo @ org.hibernate.annotations.Entity (dynamicUpdate = true)

and

0
source

Source: https://habr.com/ru/post/1338131/


All Articles