merging a detached or new entity with an existing entity in hibernate/jpa best practice question

前端 未结 2 1502
無奈伤痛
無奈伤痛 2021-01-11 16:46

When the business layer creates a new entity, which logically represents an instance of an existing entity that should be updated (say they share the same business key), is

相关标签:
2条回答
  • 2021-01-11 16:49

    If your entity is a detached entity the only thing u really need to do is to invoke entityManager.merge(user). You dont need to exec any finder method. If your entity is not detached but rather new (it does not have id specified) you should find appropriate entity in the database prior performing any modification operations on that entity and merge it afterwards. i.e:

    User user = userDao.findBySomething(Criteria c);
    
    //stuff that modifies user 
    
    user = userDao.merge(user);
    
    0 讨论(0)
  • 2021-01-11 16:52

    That code will work, but setting the ID explicitly on the detached entity should not be necessary. A typical Hibernate app have a 'save' method that handles two cases:

    1. The user wanted to create a new User, so the app creates a User object with 'null' as the ID.
    2. The user queried for a list of users, and is selecting one for edit. In this case the app does a query and propagates the object to the 'save' method. The object will have an ID and the code will apply new values to it.

    Looks like something in your code isn't doing the second case in the typical way. If the 'user' object comes from some prior Hibernate query (triggered by the user clicking 'edit user' or something like that), then it will already have an ID. Thus, only the merge(user) call is needed.

    I usually do something like this:

    if (user.getId() == null)
      em.persist(user);
    else
      user = em.merge(user);
    

    Then I add code to handle optimistic locking issues (another session updated the object) and unique constraint issues (another session tried to persist something with the same business key).

    Frameworks such as Seam can make this even simpler because they propagate the Hibernate session between the controller bean methods. So even the 'merge' is not needed.

    0 讨论(0)
提交回复
热议问题