One of my worries with Hibernate was the number of entities accumulating in a Persistence Context. If I were not careful, my codes could potentially store thousands of entities in a Persistence Context. Worse, these objects could stay in memory for an extended period degrading the application’s performance. However, my fear was baseless and out of misunderstanding.
Restricting the Number of Entities in a Persistence Context
Although there is no way to restrict the number of entities in a Persistence Context, we could shorten their lifespan. We could shorten their lifespan by confining their existence within the scope of a transaction. Once our codes commit or roll back a transaction, Hibernate flushes all the entities. As a result, Hibernate effectively removes them from the Persistence Context. In Hibernate/JPA speak, we call this Transaction-Scoped Persistence Context.
However, we need to keep our transactions small to sow the full benefit of a Transaction-Scoped Persistence Context. If our codes take too much time to complete a transaction ( and multiply that with the number they run on behalf of users), we could have entities staying in a Persistence Context (or memory) longer than they should.
When we configure Spring Data with Hibernate, our codes will use the default Transaction-Scoped Persistence Context. Our entities will live in the Persistence Context until a transaction completes – commit or rollback.
Best Practices Are Your Friend
There are best practices that could help us ensure our applications are performant. One of them that sticks out concerning Transaction-Scoped Persistence Context is keeping our transactions small. This practice is essential when we change data within transactions. Another could be keeping Hibernate JPA entity classes in a persistent layer separated from the parts of the codebase and use POJO (or domain) classes to move data from and to the persistent layer.
So, get out there and use Hibernate without worrying about the number of entities a Persistence Context could hold!