Hibernate has been the most used persistence technology in our Java projects.We have optimized Hibernate usage via our own tooling such as Querydsl JPA for querying as well as best practices and conventions for other parts such as entity lifecycle handling.
Hibernate provides multiple methods for persisting entities with slightly different semantics.To understand the methods better it is good to understand the different states Hibernate managed entities go through.The starting point for new entities is the transient state.Transient entities are unknown to any Hibernate session and don’t have any database identity attached. save will assign the database identity value to the entity’s id property, but might not do any SQL INSERTs.Session.save() should be seen as the way to register an entity with Hibernate.
The persistent state is the state loaded and queried entities are in.Also transient entities become persistent when saved via calls.Detached entities do have a database identity, but are not attached to a running entity.Detached entities are usually used when entities are used in the view rendering phase for web application with an active session or in long running conversions with multiple sessions. A common problem with Hibernate session usage is that methods are not used in the right way or unnecessary session level method calls are made.The following two cases are quite common examples of wrong API usage.It is quite common to see method calls to persist entities which are known to be managed by Hibernate.