I’m a software engineer with a passion for REST, TDD and clean code, Web Security and Data Mining. Baeldung is about all of these and more. Eugen is a DZone MVB and is not an employee of DZone and has posted 20 posts at DZone. You can read more from them at their website. View Full User Profile

The Persistence Layer with Spring Data JPA

01.20.2012
| 18617 views |
  • submit to reddit

This is the forth of a series of articles about Persistence with Spring. This article will focus on the configuration and implementation of the persistence layer with Spring 3.1, JPA and Spring Data. For a step by step introduction about setting up the Spring context using Java based configuration and the basic Maven pom for the project, see this article.

The Persistence with Spring series:

No More DAO implementations

As I discussed in a previous post, the DAO layer usually consists of a lot of boilerplate code that can and should be simplified. The advantages of such a simplification are many fold: a decrease in the number of artifacts that need to be defined and maintained, simplification and consistency of data access patterns and consistency of configuration.

Spring Data takes this simplification one step forward and makes it possible to remove the DAO implementations entirely – the interface of the DAO is now the only artifact that need to be explicitly defined.

The Spring Data managed DAO

In order to start leveraging the Spring Data programming model with JPA, a DAO interface needs to extend the JPA specific Repository interface - JpaRepository – in Spring’s interface hierarchy. This will enable Spring Data to find this interface and automatically create an implementation for it.

Also, by extending the interface we get most if not all relevant CRUD generic methods for standard data access available in the DAO.

Defining custom access method and queries

As discussed, by implementing one of the Repository interfaces, the DAO will already have some basic CRUD methods (and queries) defined and implemented. To define more specific access methods, Spring JPA supports quite a few options – you can either simply define a new method in the interface, or you can provide the actual JPQ query by using the @Query annotation.

A third option to define custom queries is to make use of JPA Named Queries, but this has the disadvantage that it either involves XML or burdening the domain class with the queries.

In addition to these, Spring Data introduces a more flexible and convenient API, similar to the JPA Criteria API, only more readable and reusable. The advantages of this API will become more pronounced when dealing with a large number of fixed queries that could potentially be more concisely expressed through a smaller number of reusable blocks that keep occurring in different combinations.

Automatic Custom Queries

When Spring Data creates a new Repository implementation, it analyzes all the methods defined by the interfaces and tries to automatically generate queries from the method name. While this has limitations, it is a very powerful and elegant way of defining new custom access methods with very little effort.

For example, if the managed entity has a name field (and the Java Bean standard getter and setter for that field), defining the findByName method in the DAO interface will automatically generate the correct query:

public interface IFooDAO extends JpaRepository< Foo, Long >{

   Foo findByName( final String name );

}

This is a relatively simple example; a much larger set of keywords is supported by query creation mechanism.

In the case that the parser cannot match the property with the domain object field, the following exception is thrown:

java.lang.IllegalArgumentException: No property nam found for type class org.rest.model.Foo


Manual Custom Queries

In addition to deriving the query from the method name, a custom query can be manually specified with the method level @Query annotation.

For even more fine grained control over the creation of queries, such as using named parameters or modifying existing queries, the reference is a good place to start.

Spring Data transaction configuration

The actual implementation of the Spring Data managed DAO – SimpleJpaRepository – uses annotations to define and configure transactions. A read only @Transactional annotation is used at the class level, which is then overridden for the non read-only methods. The rest of the transaction semantics are default, but these can be easily overridden manually per method.

Exception Translation without the template

One of the responsibilities of Spring ORM templates (JpaTemplate, HibernateTemplate) is exception translation – translating JPA exceptions – which tie the API to JPA – to Spring’s DataAccessException hierarchy.

Without the template to do that, exception translation can still be enabled by annotating the DAOs with the @Repository annotation. That, coupled with a Spring bean postprocessor will advice all @Repository beans with all the implementations of PersistenceExceptionTranslator found in the Container – to provide exception translation without using the template.

The fact that exception translation is indeed active can easily be verified with an integration test:

@Test( expected = DataAccessException.class )
public void whenAUniqueConstraintIsBroken_thenSpringSpecificExceptionIsThrown(){
   String name = "randomName";
   this.service.save( new Foo( name ) );
   this.service.save( new Foo( name ) );
}

Exception translation is done through proxies; in order for Spring to be able to create proxies around the DAO classes, these must not be declared final.

Spring Data Configuration

To activate the Spring JPA repository support, the jpa namespace is defined and used to specify the package where to DAO interfaces are located:

<?xml version="1.0" encoding="UTF-8"?>
<beans
   xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:jpa="http://www.springframework.org/schema/data/jpa"
   xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

<jpa:repositories base-package="org.rest.dao.spring" />

</beans>

At this point, there is no equivalent Java based configuration – support for it is however in the works.

The Spring Java or XML configuration

The JPA configuration with Spring 3.1 has already been carefully discussed in the previous article of this series. Spring Data also takes advantage of the Spring support for the JPA @PersistenceContext annotation which it uses to wire the EntityManager into the Spring factory bean responsible with creating the actual DAO implementations – JpaRepositoryFactoryBean.

In addition to the already discussed configuration, there is one last missing piece – including the Spring Data XML configuration in the overall persistence configuration:

@Configuration
@EnableTransactionManagement
@ImportResource( "classpath*:*springDataConfig.xml" )
public class PersistenceJPAConfig{
   ...
}

The Maven configuration

In addition to the Maven configuration for JPA defined in a previous article, the spring-data-jpa dependency is addeed:

<dependency>
   <groupId>org.springframework.data</groupId>
   <artifactId>spring-data-jpa</artifactId>
   <version>1.0.2.RELEASE</version>
</dependency>

Conclusion

This article covered the configuration and implementation of the persistence layer with Spring 3.1, JPA 2 and Spring JPA (part of the Spring Data umbrella project), using both XML and Java based configuration. The various method of defining more advanced custom queries are discussed, as well as configuration with the new jpa namespace and transactional semantics. The final result is a new and elegant take on data access with Spring, with almost no actual implementation work. You can check out the full implementation in the github project.

From the original The Persistence Layer with Spring Data JPA of the Persistence with Spring series
Published at DZone with permission of Eugen Paraschiv, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Afandi Merathi replied on Fri, 2012/03/16 - 12:13pm

Why is it a problem to "burden" the domain class with queries? The queries must live some where. The domain class seems as good a place as any for these queries.

Also, the idea that I must use Spring to simplify my JPA raises red flags. Spring is not simple. Spring is huge, sprawling, and gets bigger and more invasive with each new version. Spring is poorly documented (maybe on purpose, to encourage support contracts) and full of unexplained magic.

Kar Bro replied on Fri, 2012/08/03 - 12:14pm in response to: Afandi Merathi

well said!

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.