开发者

JPA: What is the efficient way of merging detached object?

Technologies: Spring, Hibernate, JSR-303, JQuery

Platform: Windows

I am trying to implement a simple update use case. Please see DAO/Service/Controller Source Code Link

Class2 contains many properties including Class1. The Class2Controller utilizes Spring to create a new Class2 object and bind HttpRequest object parameters to Class2. It then calls Service which in turn calls DAO. In DAO, what is the most efficient way of updating this new Class2 object to database?

Option 1:

  • Currently in DAO, I retrieve Class2 object from Database.

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

  • Update retrieved object with properties from request object and commit

    tx.begin();
    class2Persisted.setClass1(class2Request.getClass1());
    em.merge(class2Request);
    tx.commit();
    
  • Ab开发者_如何学JAVAove, I am only updating one property using setClass1. But there are many properties in Class2 that will need to be updated. It there other efficient way of merging class2Persisted with class2Request at object level instead of at each property level?

Option 2

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

  • I realized that option 2 is not a viable option. Please see another issue link that I encountered previously. Hibernate will try to load associated objects and will throw EntityNotFoundException without my custom constraint @IdMustExist getting a chance to validate.

Please suggest if you have any other suggestions.


You should use, dynamic-update=true for updating the entity/table & it is highly optimized and will only update the columns whose value is changed & does not include all fields.

You can use via annotation driven pojo @org.hibernate.annotations.Entity(dynamicUpdate = true)

and

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜