Pages

Monday, February 10, 2014

Spring-data-jpa Tutorial

Spring-data-jpa is one of my favorite Spring projects. This is probably because writing and editing SQL is way down my list of 'fun things to do'. The Spring-data project allows you to just write an interface for the repository and leave the actual implementation to the library. If you are familiar with Ruby it's similar to how ActiveRecord works.

All of the source code for this tutorial can be found on here.

BuildScript

I'll start off with the build script. Pretty simple and straightforward. We are using Hibernate as our JPA provider, but any should work fine. For this tutorial I'm also using the in-memory database HSQLDB. Even in real projects I like to include HSQLDB for testing. It allows us to have unit tests that hit an actual database but are still fast and work if you aren't connected to a work VPN.


Java Configuration

To enable the spring-data-jpa repositories add the annotation @EnableJpaRepositories and provide it with the package(s) that contain repositories. A couple of things to notice about this configuration file is that we tell Spring how to close the database when it is shutdown (@Bean(destroyMethod = "shutdown")). Failure to do this can lead to all kinds of weirdness. The second thing I wanted to point out are the properties at the bottom. Among some other things this will load the schema from the annotations in the Java files and create a file called schema.sql which you can use to create your database. This is super useful for testing using an in-memory database or as a base for creating your production database.


The Domain and Repository

The domain is annotated like you've been doing using JPA or Hibernate. The real magic is the repository. It's just an interface. All the implementation details are hidden away in the spring-data-jpa project. For the majority of your CRUD methods you can use the methods provided or create your own using just the method signature. If you need more control you can use the @Query annotation and provide your own SQL.


A test

A test to make sure everything works

If this has piqued your interest I highly recommend reading through the spring-data-jpa documentation. It's relatively short and very well written in my opinion.

No comments:

Post a Comment