In previous post I showed how to setup a sample project with JPA and Hibernate.
Even though it wasn't difficult, there was a main disadvantage - we need to do a lot of coding around our DAO objects even if we want only simple operations.
Spring Data JPA helps us reduce data access coding.
Let's start with defining dependencies:
Compared to previous project there are more dependencies because of Spring. spring-test is needed to allow our test use the spring context. And this time we're going o use HSQLDB.
pesistence.xml is much smaller because the persistence configuration will be defined in spring context.
Please note that Hibernate is still the persistence provider. The Person class is exactly the same as before.
The context is defined as:
We need to specify dataSource, entityManagerFactory and transactionManager.
The pl.mjedynak package will be scanned by spring to do autowiring.
Spring Data JPA introduces the concept of repository which is higher level of abstraction than the DAO.
In our context we define a package with the repositories.
The only thing to do to be able to manage our Person class is to create an interface that will extend CrudRepository - it gives us basic operations like save, find, delete etc.
We can of course expand it with more sophisticated methods if we want.
The integration test is almost the same as before, except it needs to use spring context.
The whole project can be found at: https://github.com/mjedynak/spring-data-jpa-example