Why I think Spring Data repositories are awesome – Part 1

I have been using Play Framework from version 1.2. Currently I’m using 2.2, which comes with a simple Ebean ORM but after reading few comments I realized it won’t be good enough for more complex projects. There is nothing worse than to realize in the middle of the project that some bug is causing your app not to work.

I looked around and noticed Spring Data. At first I didn’t put much effort in it but after checking the docs I realized it’s awesome solution. Only problem is that I doesn’t work out of the box with the Play Framework. There are few example projects on github, for me the only working was https://github.com/jamesward/play-java-spring.

I strongly advise you to check the code, because it’s show how to combine Play Framework with Spring Data. At the same time it shows how Dependency Injection works, how you define repositories and how to use them in controllers.

How it works

The basic logic is that Spring Data offers basic repositories for basic operations like saving, finding, deleting etc. Let’s imagine we have an entity Post.

I’m not going into details how to create an entity. There are many great tutorials around. For the entity we create a repository

1. We extended CrudRepository. CRUD stands for Create, Read, Update and Delete. It’s means that CrudRepository probably has some methods for creating, reading, updating and deleting posts. If we check the source of CrudRepository, it enables us to that.

2. We added annotation @Repository so Spring knows to find it correctly and inject it.

3. We extended CrudRepository where Post is out entity and Long is type of the primary key. Based on there 2 attributes, Spring knows how to correctly build queries.

Let’s take it for a spin

We put the example in 1 method for the sake of simplicity. Point is that we can simply retrieve, insert, update and delete Post entity. Spring handles building the queries, converting to objects and all other things. Again, check the example on github I mentined before so you know how to correctly define Controller, what @AutoWired does and why method index() is not static any more.

I have been using Spring Data for some time and there was not a single situation I couldn’t solve. I think the guys at Spring did a really good job. The simplicity on one side and ability to solve even most complex scenarios makes it really awesome.

More to come

In the next part we are going to check how to make a more complex queries by just defining methods name. We will also check how to include paging, sorting and how to run really really really complex queries.