Jazoon 2012: Spring Data JPA – Repositories done right

4. July, 2012

Oliver Gierke presented “Spring Data JPA – Repositories done right” at the Jazoon. The motto of Spring Data could be “deleted code doesn’t contain bugs.” From the web site:

Spring Data makes it easier to build Spring-powered applications that use new data access technologies such as non-relational databases, map-reduce frameworks, and cloud based data services as well as provide improved support for relational database technologies.

Spring Data is an umbrella open source project which contains many subprojects that are specific to a given database. The projects are developed by working together with many of the companies and developers that are behind these exciting technologies.

When you use any form of JPA, you will eventually end up with DAOs which contain many boring methods: getById(), getByName(), getByWhatever(), save(), delete(). How do you like this implementation:

interface MyBaseRepository<T, ID extends Serializable> extends Repository<T, ID> {
  T findOne(ID id);
  T save(T entity);
}

interface UserRepository extends MyBaseRepository {
  User findByEmailAddress(EmailAddress emailAddress);
}

“Wait a minute,” I can hear you think, “these are just interfaces. Where is the implementation?”

That is the implementation. You can now inject those interfaces as DAOs and call the methods. Behind the scenes, Spring will generate a proxy for you that actually implements the methods. 0 lines of code for you to write for 95% of the basic DAO methods.

The queries can even be more complex:

List findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

The method will generate SQL that searches by those two columns. See the documentation for more examples how you can write queries that use joins.

On top of that, they built a REST exporter which exposes your DAO interfaces with a REST API to a web browser plus a web front end to explore the repository, to run the queries and to create new objects. Impressive.