Wednesday 6 February 2013

Spring Data JPA sample project

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 dataSourceentityManagerFactory 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

3 comments:

  1. Mike, your example compiles using
    mvn clean package

    I am new to Spring Data and I will highly appreciate if you can help how to execute this under tomcat or stand alone.

    ReplyDelete
  2. It is just a matter of changing your spring context configuration in your existing project by adding the beans defined above.
    If you're looking for a way to simply create executable project, I'd suggest trying:
    http://spring.io/guides/gs/spring-boot/
    or even checking spring boot data jpa sample project:
    https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-data-jpa

    ReplyDelete
  3. Thanks Michael for blogging about your approach accessing MarkLogic server via a repository-style interface, I felt inspired and integrated it with Spring Boot over at: https://github.com/nikos/springboot-marklogic-sample/
    Cheers, Niko

    ReplyDelete