Object-relational Mapping Using JPA, Hibernate and Spring Data JPA. Comparing the approaches of persisting entities
Comparing the approaches of persisting entities
We have followed the implementation of an application interacting with a database and that uses, alternatively, JPA, Hibernate native, and Spring Data JPA. Our purpose was to analyze each approach and how the needed configuration and the code to be written varies.
With JPA, we used its general API and needed a persistence provider. We may switch between persistence providers from the configuration.
We needed explicit management of the EntityManagerFactory, EntityManager, and transactions. The way the configuration is done and the amount of code to be written is similar to the Hibernate native approach. We may switch to the JPA approach by constructing an EntityManagerFactory from a Hibernate native configuration.
We needed explicit management of the SessionFactory, Session, and transactions. The way the configuration is done and the amount of code to be written is similar to the JPA approach. We may switch to the Hibernate native approach by unwrapping a SessionFactory from an EntityManagerFactory or a Session from an EntityManager.
With Spring Data JPA, we needed the additional Spring Data dependencies in the project. The configuration part also takes care of the creation of the beans needed for the project, including the transaction manager.
The repository interface needs only to be declared, and Spring Data will create an implementation for it as a proxy class with generated methods that interact with the database. We may use these methods directly, as they are generated by the framework, without taking care of defining them by ourselves.
The needed repository is injected and not explicitly created by the programmer. The amount of code to be written is the shortest from all these approaches, as the configuration part has taken most of the burden.