Java Hibernate save of differs from persist of

  • 2020-04-01 04:33:58
  • OfStack

Hibernate provides a persist() method that is almost identical to the save() function in part to take care of JPA usage habits. On the other hand, there is another difference between the save() and persist() methods: when a persistent object is saved using the save() method, the method returns the value of the persistent object's identity property (that is, the primary key value for the corresponding record). But when you use the persist() method to save a persistent object, it does not return any values. Because the save() method needs to immediately return the persistent object's identity property, the program executing save() will immediately insert the data corresponding to the persistent object into the database. Persist (), on the other hand, ensures that it is not immediately converted to an insert statement when it is called outside of a thing, which is useful, especially if we encapsulate a long session flow.

Here is a clear distinction. (you can follow up with SRC to see that the implementation steps are similar, but there are still subtle differences.)
Main content differences:
1. Persist persists a transient instance, but does not "guarantee" that the identifier (the property corresponding to the identifier primary key) is immediately filled into the persistent instance, and the identifier filling may be delayed until flush.
2, save, persist an instance of a transient identifier, generate it in time, it returns an identifier, so it will immediately execute an Sql insert

Other comments:


Save method

When a persistent object is saved, this method returns the value of the identity property (that is, the primary key) of the persistent object.
This method immediately inserts the corresponding data of the persistent object into the database.

Persist method

This method does not return any values.

Ensure that when it is called outside of a transaction, it is not immediately converted to an insert statement.
Suitable for long session flows.


Related articles: