Friday, July 13, 2012

Spring Data JPA - How To

Spring Data JPA - in a few minutes

Spring Data JPA is a fantastic tool that take so much of the boiler plate out of the JPA process and leaves you to get down to the nitty gritty.  To get it up and running and supporting your basic CRUD functions, here's a couple of steps I use.

Maven Setup (yes, I'm still using Maven)

- grab the latest release packages of spring data jpa

Note: 1.1.0.RELEASE has an auto dependency on spring-tx.3.2.0.M1 and spring-orm.3.2.0.M1 which can cause some headaches in STS.  Override this by explicitly declaring 3.1.0.RELEASE versions of both and you should be good

Simple Entity

here's a simple target entity marked up with regular old JPA annotations

Simple Entity DAO

here's a Spring Data JPA DAO interface extending the JpaRepository

(that's it by the way, no implementation of this interface, nothing)

The Spring Work

i like to keep a separation of concerns for the stuff that changes (resource references) and the stuff that doesn't (EntityManagerFactory) so i'll create two files

first the spring data magic

Note: I'm using spring-orm.3.1.0 so i don't need to use a persistence.xml if i'm using annotations

and now my resources (database setup stuff)

A Unit Test

and now here's a quick sample JUnit test that tests for optimistic locking issues (version changes outside of EntityManager

Wrap Up

imho, Spring Data JPA is one of the best things to happen since Hibernate.  really increases developer productivity and gets them away from grinding out boilerplate and into the tricky stuff where they should be focused.   the people on Spring Data JPA did a great job, go and have a look at their stuff

No comments:

Post a Comment