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

前端 未结 2 1524
無奈伤痛
無奈伤痛 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);
    

提交回复
热议问题