The reason why Hibernate provides a persist() method that is almost exactly similar to the save() function is to take care of JPA usage habits. On the other hand, there is another difference between save() and persist() methods: when using save() method to save a persistent object, the method returns the identifier attribute value of the persistent object (that is, the primary key value corresponding to the record); but when using persist() method to save a persistent object, the method does not have any return value. Because the save() method needs to return the identity attribute of the persistent object immediately, the program execution save() will immediately insert the data corresponding to the persistent object into the database; while persist() ensures that when it is called outside of a thing, it is not immediately converted into an insert statement. This function is very useful, especially when we encapsulate a long session process, the persist() method is particularly important.
A clear distinction is given here. (You can follow SRC to see. Although the implementation steps are similar, there are still subtle differences)
Main content differences:
1. Persist persists a transient instance, but does not guarantee that the identifier (the attribute corresponding to the identifier primary key) will be immediately filled in the persistent instance, and the fill in the identifier may be delayed until flush.
2. Save, persists an identifier for a transient instance, and generates it in time. It needs to return the identifier, so it will immediately execute Sql insert
Other netizens’ explanations:
Save method
When saving a persisted object, this method returns the identifier attribute value (i.e., the primary key) of the persisted object.
This method will immediately insert the corresponding data of the persistent object into the database.
persist method
This method returns no value.
Ensure that when it is called outside of a transaction, it is not immediately converted to an insert statement.
Suitable for long session flows.