hibernate envers: merge & saveOrUpdate

后端 未结 2 1224
既然无缘
既然无缘 2021-01-03 09:59

I am working on an spring-hibernate-envers application. After lot of googling things are finally working for me but i have still got couple of questions.

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-03 10:28

    Hibernate Reference says:

    saveOrUpdate() does the following:

    • if the object is already persistent in this session, do nothing
    • if another object associated with the session has the same identifier, throw an exception
    • if the object has no identifier property, save() it
    • if the object's identifier has the value assigned to a newly instantiated object, save() it
    • if the object is versioned by a or , and the version property value is the same value assigned to a newly instantiated object, save() it
    • otherwise update() the object

    and merge() is very different:

    • if there is a persistent instance with the same identifier currently associated with the session, copy the state of the given object onto the persistent instance
    • if there is no persistent instance currently associated with the session, try to load it from the database, or create a new persistent instance
    • the persistent instance is returned
    • the given instance does not become associated with the session, it remains detached

    It means that you can use saveOrUpdate() if you are sure that the object with the same identifier is not associated with the session. Otherwise you should use merge().

    The following code

    entity=merge(entity);
    saveOrUpdate(entity); 
    

    works because the result of merge() is a persistent object, therefore it's ignored by saveOrUpdate(), so that the second line doesn't make any sense.

提交回复
热议问题