Month: November 2018

Jackson

Spring ORM example – JPA, Hibernate, Transaction

Welcome to the Spring ORM Example Tutorial. Today we will look into Spring ORM example using Hibernate JPA transaction management. I will show you a very simple example of Spring standalone application with following features.
  • Dependency Injection (@Autowired annotation)
  • JPA EntityManager (provided by Hibernate)
  • Annotated transactional methods (@Transactional annotation)

Spring ORM Example

spring orm example, spring orm, spring jpa hibernate example, spring hibernate transaction management, spring hibernate jpa

I have used in-memory database for Spring ORM example, so no need for any database setup (but you can change it to any other database in the spring.xml datasource section). This is a Spring ORM standalone application to minimize all dependencies (but you can easily change it to a web project by configuration if you get familiar with spring).

NOTE: For Spring AOP based Transactional (without @Transactional annotation) method resolution approach please check this tutorial: Spring ORM AOP Transaction Management.

Below image shows our final Spring ORM example project.

Spring ORM, Spring ORM Example, Spring ORM JPA Hibernate

 

Let’s go through each of the Spring ORM example project components one by one.

Spring ORM Maven dependencies

Below is our final pom.xml file having Spring ORM dependencies. We have used Spring 4 and Hibernate 4 in our Spring ORM example.

  • We need spring-context and spring-orm as Spring dependencies.
  • We use hibernate-entitymanager for Hibernate as JPA implementation. hibernate-entitymanager is dependent on hibernate-core this why we don’t have to put hibernate-core in pom.xml explicitly. It’s being pulled into our project through maven transitive dependencies.
  • We also need JDBC driver as dependency for database access. We are using HSQLDB that contains the JDBC driver and a working in memory database.

Spring ORM Model Class

We can use standard JPA annotations for mapping in our model beans because Hibernate provides JPA implementation.

We use @Entity and @Id JPA annotations to qualify our POJO as an Entity and to define it’s primary key.

Spring ORM DAO Class

We create a very simple DAO class that provides persist and findALL methods.

  • @Component is Spring annotation that tell the Spring container that we can use this class through Spring IoC (Dependency Injection).
  • We use JPA @PersistenceContext annotation that indicate dependency injection to an EntityManager. Spring injects a proper instance of EntityManager according to the spring.xml configuration.

Spring ORM Service Class

Our simple service class has 2 write and 1 read methods – add, addAll and listAll.

 

  • We use Spring @Autowired annotation to inject ProductDao in our service class.
  • We want to use transaction management, so methods are annotated with @Transactional Spring annotation. The listAll method only reads the database so we set the @Transactional annotation to read-only for optimisation.

Spring ORM Example Bean Configuration XML

Our spring ORM example project java classes are ready, let’s look at our spring bean configuration file now.

spring.xml

  1. First we tell spring that we want to use classpath scanning for Spring components (Services, DAOs) rather than defining them one by one in spring xml. We have also enabled Spring annotation detection.
  2. Adding the datasource, that is currently HSQLDB in-memory database.
  3. We set up a JPA EntityManagerFactory that will used by the application to obtain an EntityManager. Spring supports 3 different ways to do this, we have used LocalContainerEntityManagerFactoryBean for full JPA capabilities.We set LocalContainerEntityManagerFactoryBean attributes as:
    1. packagesToScan attribute that points to our model classes package.
    2. datasource defined earlier in spring configuration file.
    3. jpaVendorAdapter as Hibernate and setting some hibernate properties.
  4. We create Spring PlatformTransactionManager instance as a JpaTransactionManager. This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
  5. We enable the configuration of transactional behavior based on annotations, and we set the transactionManager we created.

Spring ORM Hibernate JPA Example Test Program

Our spring ORM JPA Hibernate example project is ready, so let’s write a test program for our application.

You can see how easily we can start the Spring container from a main method. We are getting our first dependency injected entry point, the service class instance. ProductDao class reference injected to the ProductService class after the spring context is initialized.

After we got ProducService instance, we can test it’s methods, all method call will be transactional due to Spring’s proxy mechanism. We also test rollback in this example.

If you run above spring ORM example test program, you will get below logs.

Note that the second transaction is rolled back, this why product list didn’t changed.

If you use log4j.properties file from attached source, you can see what’s going on under the hood.

References:
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html

You can download the final Spring ORM JPA Hibernate Example project from below link and play around with it to learn more.

Spring Data JPA – Reference Documentation

 

Spring Data JPA – Reference Documentation

Authors

Oliver Gierke

Copies of this document may be made for your own use and for
distribution to others, provided that you do not charge any fee for such
copies and further provided that each copy contains this Copyright
Notice, whether distributed in print or electronically.


Part I. Reference Documentation

Chapter 1. Repositories

1.1. Introduction

Implementing a data access layer of an application has been
cumbersome for quite a while. Too much boilerplate code had to be written.
Domain classes were anemic and not designed in a real object oriented or
domain driven manner.

Using both of these technologies makes developers life a lot easier
regarding rich domain model’s persistence. Nevertheless the amount of
boilerplate code to implement repositories especially is still quite high.
So the goal of the repository abstraction of Spring Data is to reduce the
effort to implement data access layers for various persistence stores
significantly.

The following chapters will introduce the core concepts and
interfaces of Spring Data repositories in general for detailled
information on the specific features of a particular store consult the
later chapters of this document.

[Note] Note
As this part of the documentation is pulled in from Spring Data
Commons we have to decide for a particular module to be used as example.
The configuration and code samples in this chapter are using the JPA
module. Make sure you adapt e.g. the XML namespace declaration, types to
be extended to the equivalents of the module you’re actually
using.

1.2. Core concepts

The central interface in Spring Data repository abstraction is
Repository (probably not that much of a
surprise). It is typeable to the domain class to manage as well as the id
type of the domain class. This interface mainly acts as marker interface
to capture the types to deal with and help us when discovering interfaces
that extend this one. Beyond that there’s
CrudRepository which provides some
sophisticated functionality around CRUD for the entity being
managed.

Example 1.1. CrudRepository interface

public interface CrudRepository<T, ID extends Serializable>
    extends Repository<T, ID> {
                                                                                         (1)
    <S extends T> S save(S entity);
                                                                                         (2)
    T findOne(ID primaryKey);
                                                                                         (3)
    Iterable<T> findAll();

    Long count();
                                                                                         (4)
    void delete(T entity);
                                                                                         (5)
    boolean exists(ID primaryKey);
                                                                                         (6)
    // … more functionality omitted.
}
1 Saves the given entity.
2 Returns the entity identified by the given id.
3 Returns all entities.
4 Returns the number of entities.
5 Deletes the given entity.
6 Returns whether an entity with the given id exists.

 

Usually we will have persistence technology specific sub-interfaces
to include additional technology specific methods. We will now ship
implementations for a variety of Spring Data modules that implement this
interface.

On top of the CrudRepository there is
a PagingAndSortingRepository abstraction
that adds additional methods to ease paginated access to entities:

Example 1.2. PagingAndSortingRepository

public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> {

    Iterable<T> findAll(Sort sort);

    Page<T> findAll(Pageable pageable);
}

 

Accessing the second page of User by a page
size of 20 you could simply do something like this:

PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(new PageRequest(1, 20));

1.3. Query methods

Next to standard CRUD functionality repositories are usually queries
on the underlying datastore. With Spring Data declaring those queries
becomes a four-step process:

  1. Declare an interface extending
    Repository or one of its sub-interfaces
    and type it to the domain class it shall handle.

    public interface PersonRepository extends Repository<User, Long> { … }
  2. Declare query methods on the interface.
    List<Person> findByLastname(String lastname);
  3. Setup Spring to create proxy instances for those
    interfaces.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns="http://www.springframework.org/schema/data/jpa"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
    
      <repositories base-package="com.acme.repositories" />
    
    </beans>
    [Note] Note
    Note that we use the JPA namespace here just by example. If
    you’re using the repository abstraction for any other store you need
    to change this to the appropriate namespace declaration of your
    store module which should be exchanging jpa in favor of
    e.g. mongodb.
  4. Get the repository instance injected and use it.
    public class SomeClient {
    
      @Autowired
      private PersonRepository repository;
    
      public void doSomething() {
        List<Person> persons = repository.findByLastname("Matthews");
      }

At this stage we barely scratched the surface of what’s possible
with the repositories but the general approach should be clear. Let’s go
through each of these steps and figure out details and various options
that you have at each stage.

1.3.1. Defining repository interfaces

As a very first step you define a domain class specific repository
interface. It’s got to extend Repository
and be typed to the domain class and an ID type. If you want to expose
CRUD methods for that domain type, extend
CrudRepository instead of
Repository.

1.3.1.1. Fine tuning repository definition

Usually you will have your repository interface extend
Repository,
CrudRepository or
PagingAndSortingRepository. If you
don’t like extending Spring Data interfaces at all you can also
annotate your repository interface with
@RepositoryDefinition. Extending
CrudRepository will expose a complete
set of methods to manipulate your entities. If you would rather be
selective about the methods being exposed, simply copy the ones you
want to expose from CrudRepository into
your domain repository.

Example 1.3. Selectively exposing CRUD methods

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

interface UserRepository extends MyBaseRepository<User, Long> {

  User findByEmailAddress(EmailAddress emailAddress);
}

 

In the first step we define a common base interface for all our
domain repositories and expose findOne(…) as
well as save(…).These methods will be routed
into the base repository implementation of the store of your choice
because they are matching the method signatures in
CrudRepository. So our
UserRepository will now be able to save
users, find single ones by id as well as triggering a query to find
Users by their email address.

1.3.2. Defining query methods

1.3.2.1. Query lookup strategies

The next thing we have to discuss is the definition of query
methods. There are two main ways that the repository proxy is able to
come up with the store specific query from the method name. The first
option is to derive the query from the method name directly, the
second is using some kind of additionally created query. What detailed
options are available pretty much depends on the actual store,
however, there’s got to be some algorithm that decides what actual
query is created.

There are three strategies available for the repository
infrastructure to resolve the query. The strategy to be used can be
configured at the namespace through the
query-lookup-strategy attribute. However, It might be the
case that some of the strategies are not supported for specific
datastores. Here are your options:

CREATE

This strategy will try to construct a store specific query
from the query method’s name. The general approach is to remove a
given set of well-known prefixes from the method name and parse the
rest of the method. Read more about query construction in Section 1.3.2.2, “Query creation”.

USE_DECLARED_QUERY

This strategy tries to find a declared query which will be
used for execution first. The query could be defined by an
annotation somewhere or declared by other means. Please consult the
documentation of the specific store to find out what options are
available for that store. If the repository infrastructure does not
find a declared query for the method at bootstrap time it will
fail.

CREATE_IF_NOT_FOUND (default)

This strategy is actually a combination of CREATE
and USE_DECLARED_QUERY. It will try to lookup a
declared query first but create a custom method name based query if
no declared query was found. This is the default lookup strategy and
thus will be used if you don’t configure anything explicitly. It
allows quick query definition by method names but also custom tuning
of these queries by introducing declared queries as needed.

1.3.2.2. Query creation

The query builder mechanism built into Spring Data repository
infrastructure is useful to build constraining queries over entities
of the repository. We will strip the prefixes find…By,
read…By, as well as get…By from the method
and start parsing the rest of it. The introducing clause can contain
further expressions such as a Distinct to set a distinct
flag on the query to be created. However, the first By
acts as delimiter to indicate the start of the actual criterias. At a
very basic level you can define conditions on entity properties and
concatenate them with AND and OR.

Example 1.4. Query creation from method names

public interface PersonRepository extends Repository<User, Long> {

  List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

  // Enables the distinct flag for the query
  List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
  List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);

  // Enabling ignoring case for an individual property
  List<Person> findByLastnameIgnoreCase(String lastname);
  // Enabling ignoring case for all suitable properties
  List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);

  // Enabling static ORDER BY for a query
  List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
  List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
}

 

The actual result of parsing that method will of course depend
on the persistence store we create the query for, however, there are
some general things to notice. The expressions are usually property
traversals combined with operators that can be concatenated. As you
can see in the example you can combine property expressions with And
and Or. Beyond that you also get support for various operators like
Between, LessThan,
GreaterThan, Like for the
property expressions. As the operators supported can vary from
datastore to datastore please consult the according part of the
reference documentation.

As you can see the method parser also supports setting an ignore
case flag for individual properties (e.g.
findByLastnameIgnoreCase(…)) or for all
properties of a type that support ignoring case (i.e. usually
Strings, e.g.
findByLastnameAndFirstnameAllIgnoreCase(…)).
Whether ignoring cases is supported my differ from store to store, so
consult the relevant sections of the store specific query method
reference docs.

Static ordering can be applied by appending an
OrderBy clause to the query method referencing a property
and providing a sorting direction (Asc or
Desc). To create a query method that supports dynamic
sorting have a look at Section 1.3.2.3, “Special parameter handling”.

1.3.2.2.1. Property expressions

Property expressions can just refer to a direct property of
the managed entity (as you just saw in the example above). On query
creation time we already make sure that the parsed property is at a
property of the managed domain class. However, you can also define
constraints by traversing nested properties. Assume
Persons have Addresses
with ZipCodes. In that case a method name
of

List<Person> findByAddressZipCode(ZipCode zipCode);

will create the property traversal
x.address.zipCode. The resolution algorithm starts with
interpreting the entire part (AddressZipCode) as
property and checks the domain class for a property with that name
(uncapitalized). If it succeeds it just uses that. If not it starts
splitting up the source at the camel case parts from the right side
into a head and a tail and tries to find the according property,
e.g. AddressZip and Code. If
we find a property with that head we take the tail and continue
building the tree down from there. As in our case the first split
does not match we move the split point to the left
(Address, ZipCode).

Although this should work for most cases, there might be cases
where the algorithm could select the wrong property. Suppose our
Person class has an addressZip
property as well. Then our algorithm would match in the first split
round already and essentially choose the wrong property and finally
fail (as the type of addressZip probably has
no code property). To resolve this ambiguity you can use
_ inside your method name to manually define
traversal points. So our method name would end up like so:

List<Person> findByAddress_ZipCode(ZipCode zipCode);

1.3.2.3. Special parameter handling

To hand parameters to your query you simply define method
parameters as already seen in the examples above. Besides that we will
recognizes certain specific types to apply pagination and sorting to
your queries dynamically.

Example 1.5. Using Pageable and Sort in query methods

Page<User> findByLastname(String lastname, Pageable pageable);

List<User> findByLastname(String lastname, Sort sort);

List<User> findByLastname(String lastname, Pageable pageable);

 

The first method allows you to pass a
org.springframework.data.domain.Pageable instance to the
query method to dynamically add paging to your statically defined
query. Sorting options are handed via the
Pageable instance too. If you only need
sorting, simply add an
org.springframework.data.domain.Sort parameter to your
method. As you also can see, simply returning a
List is possible as well. We will then
not retrieve the additional metadata required to build the actual
Page instance but rather simply
restrict the query to lookup only the given range of entities.

[Note] Note
To find out how many pages you get for a query entirely we
have to trigger an additional count query. This will be derived from
the query you actually trigger by default.

1.3.3. Creating repository instances

So now the question is how to create instances and bean
definitions for the repository interfaces defined.

1.3.3.1. XML Configuration

The easiest way to do so is by using the Spring namespace that
is shipped with each Spring Data module that supports the repository
mechanism. Each of those includes a repositories element that allows
you to simply define a base package that Spring will scan for
you.

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

  <repositories base-package="com.acme.repositories" />

</beans:beans>

In this case we instruct Spring to scan
com.acme.repositories and all its sub packages for
interfaces extending Repository or one
of its sub-interfaces. For each interface found it will register the
persistence technology specific
FactoryBean to create the according
proxies that handle invocations of the query methods. Each of these
beans will be registered under a bean name that is derived from the
interface name, so an interface of
UserRepository would be registered
under userRepository. The base-package
attribute allows the use of wildcards, so that you can have a pattern
of scanned packages.

Using filters

By default we will pick up every interface extending the
persistence technology specific
Repository sub-interface located
underneath the configured base package and create a bean instance
for it. However, you might want finer grained control over which
interfaces bean instances get created for. To do this we support the
use of <include-filter /> and
<exclude-filter /> elements inside
<repositories />. The semantics are exactly
equivalent to the elements in Spring’s context namespace. For
details see Spring reference documentation on these
elements.

E.g. to exclude certain interfaces from instantiation as
repository, you could use the following configuration:

Example 1.6. Using exclude-filter element

<repositories base-package="com.acme.repositories">
  <context:exclude-filter type="regex" expression=".*SomeRepository" />
</repositories>

This would exclude all interfaces ending in
SomeRepository from being
instantiated.

 

1.3.3.2. JavaConfig

The repository infrastructure can also be triggered using a
store-specific
@Enable${store}Repositories annotation
on a JavaConfig class. For an introduction into Java based
configuration of the Spring container please have a look at the
reference documentation.[1]

A sample configuration to enable Spring Data repositories would
look something like this.

Example 1.7. Sample annotation based repository configuration

@Configuration
@EnableJpaRepositories("com.acme.repositories")
class ApplicationConfiguration {

  @Bean
  public EntityManagerFactory entityManagerFactory() {
    // …
  }
}

 

Note that the sample uses the JPA specific annotation which
would have to be exchanged dependingon which store module you actually
use. The same applies to the definition of the
EntityManagerFactory bean. Please
consult the sections covering the store-specific configuration.

1.3.3.3. Standalone usage

You can also use the repository infrastructure outside of a
Spring container usage. You will still need to have some of the Spring
libraries on your classpath but you can generally setup repositories
programmatically as well. The Spring Data modules providing repository
support ship a persistence technology specific
RepositoryFactory that can be used as
follows:

Example 1.8. Standalone usage of repository factory

RepositoryFactorySupport factory = … // Instantiate factory here
UserRepository repository = factory.getRepository(UserRepository.class);

 

1.4. Custom implementations

1.4.1. Adding behaviour to single repositories

Often it is necessary to provide a custom implementation for a few
repository methods. Spring Data repositories easily allow you to provide
custom repository code and integrate it with generic CRUD abstraction
and query method functionality. To enrich a repository with custom
functionality you have to define an interface and an implementation for
that functionality first and let the repository interface you provided
so far extend that custom interface.

Example 1.9. Interface for custom repository functionality

interface UserRepositoryCustom {

  public void someCustomMethod(User user);
}

 

Example 1.10. Implementation of custom repository functionality

class UserRepositoryImpl implements UserRepositoryCustom {

  public void someCustomMethod(User user) {
    // Your custom implementation
  }
}

Note that the implementation itself does not depend on
Spring Data and can be a regular Spring bean. So you can use standard
dependency injection behaviour to inject references to other beans,
take part in aspects and so on.

 

Example 1.11. Changes to the your basic repository interface

public interface UserRepository extends CrudRepository<User, Long>, UserRepositoryCustom {

  // Declare query methods here
}

Let your standard repository interface extend the custom
one. This makes CRUD and custom functionality available to
clients.

 

Configuration

If you use namespace configuration the repository infrastructure
tries to autodetect custom implementations by looking up classes in
the package we found a repository using the naming conventions
appending the namespace element’s attribute
repository-impl-postfix to the classname. This suffix
defaults to Impl.

Example 1.12. Configuration example

<repositories base-package="com.acme.repository" />

<repositories base-package="com.acme.repository" repository-impl-postfix="FooBar" />

 

The first configuration example will try to lookup a class
com.acme.repository.UserRepositoryImpl to act
as custom repository implementation, where the second example will try
to lookup
com.acme.repository.UserRepositoryFooBar.

Manual wiring

The approach above works perfectly well if your custom
implementation uses annotation based configuration and autowiring
entirely as it will be treated as any other Spring bean. If your
custom implementation bean needs some special wiring you simply
declare the bean and name it after the conventions just described. We
will then pick up the custom bean by name rather than creating an
instance.

Example 1.13. Manual wiring of custom implementations (I)

<repositories base-package="com.acme.repository" />

<beans:bean id="userRepositoryImpl" class="…">
  <!-- further configuration -->
</beans:bean>

 

1.4.2. Adding custom behaviour to all repositories

In other cases you might want to add a single method to all of
your repository interfaces. So the approach just shown is not feasible.
The first step to achieve this is adding and intermediate interface to
declare the shared behaviour

Example 1.14. An interface declaring custom shared behaviour

public interface MyRepository<T, ID extends Serializable>
  extends JpaRepository<T, ID> {

  void sharedCustomMethod(ID id);
}

 

Now your individual repository interfaces will extend this
intermediate interface instead of the
Repository interface to include the
functionality declared. The second step is to create an implementation
of this interface that extends the persistence technology specific
repository base class which will then act as a custom base class for the
repository proxies.

[Note] Note
The default behaviour of the Spring <repositories
/>
namespace is to provide an implementation for all
interfaces that fall under the base-package. This means
that if left in it’s current state, an implementation instance of
MyRepository will be created by Spring.
This is of course not desired as it is just supposed to act as an
intermediary between Repository and the
actual repository interfaces you want to define for each entity. To
exclude an interface extending
Repository from being instantiated as a
repository instance it can either be annotate it with
@NoRepositoryBean or moved out side of
the configured base-package.

Example 1.15. Custom repository base class

public class MyRepositoryImpl<T, ID extends Serializable>
  extends SimpleJpaRepository<T, ID> implements MyRepository<T, ID> {

  private EntityManager entityManager;

  // There are two constructors to choose from, either can be used.
  public MyRepositoryImpl(Class<T> domainClass, EntityManager entityManager) {
    super(domainClass, entityManager);

    // This is the recommended method for accessing inherited class dependencies.
    this.entityManager = entityManager;
  }

  public void sharedCustomMethod(ID id) {
    // implementation goes here
  }
}

 

The last step is to create a custom repository factory to replace
the default RepositoryFactoryBean that will in
turn produce a custom RepositoryFactory. The new
repository factory will then provide your
MyRepositoryImpl as the implementation of any
interfaces that extend the Repository
interface, replacing the SimpleJpaRepository
implementation you just extended.

Example 1.16. Custom repository factory bean

public class MyRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable>
  extends JpaRepositoryFactoryBean<R, T, I> {

  protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {

    return new MyRepositoryFactory(entityManager);
  }

  private static class MyRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {

    private EntityManager entityManager;

    public MyRepositoryFactory(EntityManager entityManager) {
      super(entityManager);

      this.entityManager = entityManager;
    }

    protected Object getTargetRepository(RepositoryMetadata metadata) {

      return new MyRepositoryImpl<T, I>((Class<T>) metadata.getDomainClass(), entityManager);
    }

    protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {

      // The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory
      //to check for QueryDslJpaRepository's which is out of scope.
      return MyRepository.class;
    }
  }
}

 

Finally you can either declare beans of the custom factory
directly or use the factory-class attribute of the Spring
namespace to tell the repository infrastructure to use your custom
factory implementation.

Example 1.17. Using the custom factory with the namespace

<repositories base-package="com.acme.repository"
  factory-class="com.acme.MyRepositoryFactoryBean" />

 

1.5. Extensions

This chapter documents a set of Spring Data extensions that enable
Spring Data usage in a variety of contexts. Currently most of the
integration is targeted towards Spring MVC.

1.5.1. Domain class web binding for Spring MVC

Given you are developing a Spring MVC web applications you
typically have to resolve domain class ids from URLs. By default it’s
your task to transform that request parameter or URL part into the
domain class to hand it layers below then or execute business logic on
the entities directly. This should look something like this:

@Controller
@RequestMapping("/users")
public class UserController {

  private final UserRepository userRepository;

  @Autowired
  public UserController(UserRepository userRepository) {
    Assert.notNull(repository, "Repository must not be null!");
    userRepository = userRepository;
  }

  @RequestMapping("/{id}")
  public String showUserForm(@PathVariable("id") Long id, Model model) {
    
    // Do null check for id
    User user = userRepository.findOne(id);
    // Do null check for user

    model.addAttribute("user", user);
    return "user";
  }
}

First you pretty much have to declare a repository dependency for
each controller to lookup the entity managed by the controller or
repository respectively. Beyond that looking up the entity is
boilerplate as well as it’s always a findOne(…)
call. Fortunately Spring provides means to register custom converting
components that allow conversion between a String
value to an arbitrary type.

PropertyEditors

For versions up to Spring 3.0 simple Java
PropertyEditors had to be used. Thus,
we offer a DomainClassPropertyEditorRegistrar,
that will look up all Spring Data repositories registered in the
ApplicationContext and register a
custom PropertyEditor for the managed
domain class

<bean class="….web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="webBindingInitializer">
    <bean class="….web.bind.support.ConfigurableWebBindingInitializer">
      <property name="propertyEditorRegistrars">
        <bean class="org.springframework.data.repository.support.DomainClassPropertyEditorRegistrar" />
      </property>
    </bean>
  </property>
</bean>

If you have configured Spring MVC like this you can turn your
controller into the following that reduces a lot of the clutter and
boilerplate.

@Controller
@RequestMapping("/users")
public class UserController {

  @RequestMapping("/{id}")
  public String showUserForm(@PathVariable("id") User user, Model model) {

    model.addAttribute("user", user);
    return "userForm";
  }
}

ConversionService

As of Spring 3.0 the
PropertyEditor support is superseeded
by a new conversion infrstructure that leaves all the drawbacks of
PropertyEditors behind and uses a
stateless X to Y conversion approach. We now ship with a
DomainClassConverter that pretty much mimics
the behaviour of
DomainClassPropertyEditorRegistrar. To
configure, simply declare a bean instance and pipe the
ConversionService being used into it’s
constructor:

<mvc:annotation-driven conversion-service="conversionService" />

<bean class="org.springframework.data.repository.support.DomainClassConverter">
  <constructor-arg ref="conversionService" />
</bean>

If you’re using JavaConfig you can simply extend
WebMvcConfigurationSupport and hand the
FormatingConversionService the configuration
superclass provides into the
DomainClassConverter instance you
create.

class WebConfiguration extends WebMvcConfigurationSupport {

  // Other configuration omitted

  @Bean
  public DomainClassConverter<?> domainClassConverter() {
    return new DomainClassConverter<FormattingConversionService>(mvcConversionService());
  }
}

1.5.2. Web pagination

@Controller
@RequestMapping("/users")
public class UserController {

  // DI code omitted

  @RequestMapping
  public String showUsers(Model model, HttpServletRequest request) {

    int page = Integer.parseInt(request.getParameter("page"));
    int pageSize = Integer.parseInt(request.getParameter("pageSize"));

    Pageable pageable = new PageRequest(page, pageSize);

    model.addAttribute("users", userService.getUsers(pageable));
    return "users";
  }
}

As you can see the naive approach requires the method to contain
an HttpServletRequest parameter that has
to be parsed manually. We even omitted an appropriate failure handling
which would make the code even more verbose. The bottom line is that the
controller actually shouldn’t have to handle the functionality of
extracting pagination information from the request. So we include a
PageableArgumentResolver that will do the work
for you.

<bean class="….web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="customArgumentResolvers">
    <list>
      <bean class="org.springframework.data.web.PageableArgumentResolver" />
    </list>
  </property>
</bean>

This configuration allows you to simplify controllers down to
something like this:

@Controller
@RequestMapping("/users")
public class UserController {

  @RequestMapping
  public String showUsers(Model model, Pageable pageable) {

    model.addAttribute("users", userRepository.findAll(pageable));
    return "users";
  }
}

The PageableArgumentResolver will
automatically resolve request parameters to build a
PageRequest instance. By default it will expect
the following structure for the request parameters:

Table 1.1. Request parameters evaluated by
PageableArgumentResolver

page The page you want to retrieve
page.size The size of the page you want to retrieve
page.sort The property that should be sorted by
page.sort.dir The direction that should be used for sorting

 

In case you need multiple Pageables
to be resolved from the request (for multiple tables e.g.) you can use
Spring’s @Qualifier annotation to
distinguish one from another. The request parameters then have to be
prefixed with ${qualifier}_. So a method signature like
this:

public String showUsers(Model model, 
      @Qualifier("foo") Pageable first,
      @Qualifier("bar") Pageable second) { … }

you’d have to populate foo_page and
bar_page and the according subproperties.

Defaulting

The PageableArgumentResolver will use a
PageRequest with the first page and a page size
of 10 by default and will use that in case it can’t resolve a
PageRequest from the request (because of
missing parameters e.g.). You can configure a global default on the
bean declaration directly. In case you might need controller method
specific defaults for the Pageable
simply annotate the method parameter with
@PageableDefaults and specify page
(through pageNumber), page size (through
value) as well as sort (the list of
properties to sort by) as wel as sortDir (the direction
to sort by) as annotation attributes:

public String showUsers(Model model, 
  @PageableDefaults(pageNumber = 0, value = 30) Pageable pageable) { … }

1.5.3. Repository populators

If you have been working with the JDBC module of Spring you’re
probably familiar with the support to populate a DataSource using SQL
scripts. A similar abstraction is available on the repositories level
although we don’t use SQL as data definition language as we need to be
store independent of course. Thus the populators support XML (through
Spring’s OXM abstraction) and JSON (through Jackson) to define data for
the repositories to be populated with.

Assume you have a file data.json with the
following content:

Example 1.18. Data defined in JSON

[ { "_class" : "com.acme.Person",
 "firstname" : "Dave",
  "lastname" : "Matthews" },
  { "_class" : "com.acme.Person",
 "firstname" : "Carter",
  "lastname" : "Beauford" } ]

 

You can easily populate you repositories by using the populator
elements of the repository namespace provided in Spring Data Commons. To
get the just shown data be populated to your
PersonRepository all you need to do is
the following:

Example 1.19. Declaring a Jackson repository populator

<?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:repository="http://www.springframework.org/schema/data/repository"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/repository
    http://www.springframework.org/schema/data/repository/spring-repository.xsd">

  <repository:jackson-populator location="classpath:data.json" />

</beans>

 

This declaration causes the data.json file being read,
deserialized by a Jackson ObjectMapper. The type
the JSON object will be unmarshalled to will be determined by inspecting
the _class attribute of the JSON document. We will
eventually select the appropriate repository being able to handle the
object just deserialized.

To rather use XML to define the repositories shall be populated
with you can use the unmarshaller-populator you hand one of the
marshaller options Spring OXM provides you with.

Example 1.20. Declaring an unmarshalling repository populator (using
JAXB)

<?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:repository="http://www.springframework.org/schema/data/repository"
  xmlns:oxm="http://www.springframework.org/schema/oxm"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/data/repository
    http://www.springframework.org/schema/data/repository/spring-repository.xsd
    http://www.springframework.org/schema/oxm
    http://www.springframework.org/schema/oxm/spring-oxm.xsd">

  <repository:unmarshaller-populator location="classpath:data.json" unmarshaller-ref="unmarshaller" />

  <oxm:jaxb2-marshaller contextPath="com.acme" />

</beans>

 

Chapter 2. JPA Repositories

Abstract

This chapter includes details of the JPA repository
implementation.

2.1. Introduction

2.1.1. Spring namespace

The JPA module of Spring Data contains a custom namespace that
allows defining repository beans. It also contains certain features and
element attributes that are special to JPA. Generally the JPA
repositories can be set up using the repositories
element:

Example 2.1. Setting up JPA repositories using the namespace

<?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.xsd
    http://www.springframework.org/schema/data/jpa
    http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

  <jpa:repositories base-package="com.acme.repositories" />

</beans>

 

Using this element looks up Spring Data repositories as described
in Section 1.3.3, “Creating repository instances”. Beyond that it
activates persistence exception translation for all beans annotated with
@Repository to let exceptions being
thrown by the JPA presistence providers be converted into Spring’s
DataAccessException hierarchy.

Custom namespace attributes

Beyond the default attributes of the repositories
element the JPA namespace offers additional attributes to gain more
detailled control over the setup of the repositories:

Table 2.1. Custom JPA-specific attributes of the repositories
element

entity-manager-factory-ref Explicitly wire the
EntityManagerFactory to be used
with the repositories being detected by the
repositories element. Usually used if multiple
EntityManagerFactory beans are
used within the application. If not configured we will
automatically lookup the single
EntityManagerFactory configured
in the
ApplicationContext.
transaction-manager-ref Explicitly wire the
PlatformTransactionManager to
be used with the repositories being detected by the
repositories element. Usually only necessary if
multiple transaction managers and/or
EntityManagerFactory beans have
been configured. Default to a single defined
PlatformTransactionManager
inside the current
ApplicationContext.

 

2.1.2. Annotation based configuration

The Spring Data JPA repositories support cannot only be activated
through an XML namespace but also using an annotation through
JavaConfig.

Example 2.2. Spring Data JPA repositories using JavaConfig

@Configuration
@EnableJpaRepositories
@EnableTransactionManagement
class ApplicationConfig {

  @Bean
  public DataSource dataSource() {

    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    return builder.setType(EmbeddedDatabaseType.HSQL).build();
  }

  @Bean
  public EntityManagerFactory entityManagerFactory() {

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("com.acme.domain");
    factory.setDataSource(dataSource());
    factory.afterPropertiesSet();

    return factory.getObject();
  }

  @Bean
  public PlatformTransactionManager transactionManager() {

    JpaTransactionManager txManager = new JpaTransactionManager();
    txManager.setEntityManagerFactory(entityManagerFactory());
    return txManager;
  }
}

 

The just shown configuration class sets up an embedded HSQL
database using the EmbeddedDatabaseBuilder API of
spring-jdbc. We then set up a
EntityManagerFactory and use Hibernate as
sample persistence provider. The last infrastructure component declared
here is the JpaTransactionManager. We eventually
activate Spring Data JPA repositories using the
@EnableJpaRepositories annotation which
essentially carries the same attributes as the XML namespace does. If no
base package is configured it will use the one the configuration class
resides in.

2.2. Query methods

2.2.1. Query lookup strategies

The JPA module supports defining a query manually as String or
have it being derived from the method name.

Declared queries

Although getting a query derived from the method name is quite
convenient, one might face the situation in which either the method
name parser does not support the keyword one wants to use or the
method name would get unnecessarily ugly. So you can either use JPA
named queries through a naming convention (see Section 2.2.3, “Using JPA NamedQueries” for more information) or
rather annotate your query method with
@Query (see Section 2.2.4, “Using @Query” for details).

2.2.2. Query creation

Generally the query creation mechanism for JPA works as described
in Section 1.3, “Query methods”. Here’s a short example
of what a JPA query method translates into:

Example 2.3. Query creation from method names

public interface UserRepository extends Repository<User, Long> {

  List<User> findByEmailAddressAndLastname(String emailAddress, String lastname);
}

We will create a query using the JPA criteria API from this
but essentially this translates into the following query:

select u from User u where u.emailAddress = ?1 and u.lastname = ?2

Spring Data JPA will do a property check and traverse nested
properties as described in Section 1.3.2.2.1, “Property expressions”. Here’s
an overview of the keywords supported for JPA and what a method
containing that keyword essentially translates to.

 

Table 2.2. Supported keywords inside method names

Keyword Sample JPQL snippet
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname =
?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname =
?2
Between findByStartDateBetween … where x.startDate between 1? and
?2
LessThan findByAgeLessThan … where x.age < ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter
bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter
bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter
bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname
desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection<Age>
ages)
… where x.age in ?1
NotIn findByAgeNotIn(Collection<Age>
age)
… where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false

 

[Note] Note
In and NotIn also take any subclass
of Collection as parameter as well as
arrays or varargs. For other syntactical versions of the very same
logical operator check Appendix B, Repository query keywords.

2.2.3. Using JPA NamedQueries

[Note] Note
The examples use simple <named-query />
element and @NamedQuery annotation. The queries for these
configuration elements have to be defined in JPA query language. Of
course you can use <named-native-query /> or
@NamedNativeQuery too. These elements allow you to define
the query in native SQL by losing the database platform
independence.

XML named query definition

To use XML configuration simply add the necessary
<named-query /> element to the
orm.xml JPA configuration file located in
META-INF folder of your classpath. Automatic
invocation of named queries is enabled by using some defined naming
convention. For more details see below.

Example 2.4. XML named query configuration

<named-query name="User.findByLastname">
  <query>select u from User u where u.lastname = ?1</query>
</named-query>

 

As you can see the query has a special name which will be used
to resolve it at runtime.

Annotation configuration

Annotation configuration has the advantage of not needing
another configuration file to be edited, probably lowering maintenance
costs. You pay for that benefit by the need to recompile your domain
class for every new query declaration.

Example 2.5. Annotation based named query configuration

@Entity
@NamedQuery(name = "User.findByEmailAddress",
  query = "select u from User u where u.emailAddress = ?1")
public class User {

}

 

Declaring interfaces

To allow execution of these named queries all you need to do is
to specify the UserRepository as
follows:

Example 2.6. Query method declaration in UserRepository

public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByLastname(String lastname);

  User findByEmailAddress(String emailAddress);
}

 

Spring Data will try to resolve a call to these methods to a
named query, starting with the simple name of the configured domain
class, followed by the method name separated by a dot. So the example
here would use the named queries defined above instead of trying to
create a query from the method name.

2.2.4. Using @Query

Using named queries to declare queries for entities is a valid
approach and works fine for a small number of queries. As the queries
themselves are tied to the Java method that executes them you actually
can bind them directly using the Spring Data JPA @Query
annotation rather than annotating them to the domain class. This will
free the domain class from persistence specific information and
co-locate the query to the repository interface.

Queries annotated to the query method will take precedence over
queries defined using @NamedQuery or named queries declared
in orm.xml.

Example 2.7. Declare query at the query method using
@Query

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.emailAddress = ?1")
  User findByEmailAddress(String emailAddress);
}

 

Native queries

The @Query annotation allows to
execute native queries by setting the nativeQuery flag to
true. Note, that we currently don’t support execution of pagination or
dynamic sorting for native queries as we’d have to manipulate the
actual query declared and we cannot do this reliably for native
SQL.

Example 2.8. Declare a native query at the query method using
@Query

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT FROM USERS WHERE EMAIL_ADDRESS = ?0", nativeQuery = true)
  User findByEmailAddress(String emailAddress);
}

 

2.2.5. Using named parameters

By default Spring Data JPA will use position based parameter
binding as described in all the samples above. This makes query methods
a little error prone to refactoring regarding the parameter position. To
solve this issue you can use @Param annotation to give a
method parameter a concrete name and bind the name in the query:

Example 2.9. Using named parameters

public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
  User findByLastnameOrFirstname(@Param("lastname") String lastname,
                                 @Param("firstname") String firstname);
}

Note that the method parameters are switched according to the
occurrence in the query defined.

 

2.2.6. Modifying queries

All the sections above describe how to declare queries to access a
given entity or collection of entities. Of course you can add custom
modifying behaviour by using facilities described in Section 1.4, “Custom implementations”. As this approach is
feasible for comprehensive custom functionality, you can achieve the
execution of modifying queries that actually only need parameter binding
by annotating the query method with @Modifying:

Example 2.10. Declaring manipulating queries

@Modifying
@Query("update User u set u.firstname = ?1 where u.lastname = ?2")
int setFixedFirstnameFor(String firstname, String lastname);

 

This will trigger the query annotated to the method as updating
query instead of a selecting one. As the
EntityManager might contain outdated
entities after the execution of the modifying query, we automatically
clear it (see JavaDoc of
EntityManager.clear()
for details). This will effectively drop all non-flushed changes still
pending in the EntityManager. If you
don’t wish the EntityManager to be
cleared automatically you can set
@Modifying annotation’s
clearAutomatically attribute to
false;

2.2.7. Applying query hints

To apply JPA QueryHints to the
queries declared in your repository interface you can use the
QueryHints annotation. It takes an array
of JPA QueryHint annotations plus a
boolean flag to potentially disable the hints applied to the addtional
count query triggered when applying pagination.

Example 2.11. Using QueryHints with a repository method

public interface UserRepository extends Repository<User, Long> {

  @QueryHints(value = { @QueryHint(name = "name", value = "value")}, 
              forCounting = false)
  Page<User> findByLastname(String lastname, Pageable pageable);
}

The just shown declaration would apply the configured
QueryHint for that actually query but
omit applying it to the count query triggered to calculate the total
number of pages.

 

2.3. Specifications

JPA 2 introduces a criteria API that can be used to build queries
programmatically. Writing a criteria you actually define the
where-clause of a query for a domain class. Taking another step back these
criteria can be regarded as predicate over the entity that is described by
the JPA criteria API constraints.

Spring Data JPA takes the concept of a specification from Eric
Evans’ book “Domain Driven Design”, following the same semantics and
providing an API to define such
Specifications using the JPA criteria API.
To support specifications you can extend your repository interface with
the JpaSpecificationExecutor
interface:

public interface CustomerRepository extends CrudRepository<Customer, Long>, JpaSpecificationExecutor {
 …
}

The additional interface carries methods that allow you to execute
Specifications in a variety of ways.

For example, the findAll method will return all
entities that match the specification:

List<T> findAll(Specification<T> spec);

The Specification interface is as
follows:

public interface Specification<T> {
  Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
            CriteriaBuilder builder);
}

Okay, so what is the typical use case?
Specifications can easily be used to build
an extensible set of predicates on top of an entity that then can be
combined and used with JpaRepository
without the need to declare a query (method) for every needed combination.
Here’s an example:

Example 2.12. Specifications for a Customer

public class CustomerSpecs {

  public static Specification<Customer> isLongTermCustomer() {
    return new Specification<Customer>() {
      Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
            CriteriaBuilder builder) {

         LocalDate date = new LocalDate().minusYears(2);
         return builder.lessThan(root.get(Customer_.createdAt), date);
      }
    };
  }

  public static Specification<Customer> hasSalesOfMoreThan(MontaryAmount value) {
    return new Specification<Customer>() {
      Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
            CriteriaBuilder builder) {

         // build query here
      }
    };
  }
}

 

Admittedly the amount of boilerplate leaves room for improvement
(that will hopefully be reduced by Java 8 closures) but the client side
becomes much nicer as you will see below. Besides that we have expressed
some criteria on a business requirement abstraction level and created
executable Specifications. So a client
might use a Specification as
follows:

Example 2.13. Using a simple Specification

List<Customer> customers = customerRepository.findAll(isLongTermCustomer());

 

Okay, why not simply create a query for this kind of data access?
You’re right. Using a single Specification
does not gain a lot of benefit over a plain query declaration. The power
of Specifications really shines when you
combine them to create new Specification
objects. You can achieve this through the
Specifications helper class we provide to build
expressions like this:

Example 2.14. Combined Specifications

MonetaryAmount amount = new MonetaryAmount(200.0, Currencies.DOLLAR);
List<Customer> customers = customerRepository.findAll(
  where(isLongTermCustomer()).or(hasSalesOfMoreThan(amount)));

As
you can see, Specifications offers some glue-code
methods to chain and combine
Specifications. Thus extending your data
access layer is just a matter of creating new
Specification implementations and
combining them with ones already existing.

 

2.4. Transactionality

CRUD methods on repository instances are transactional by default.
For reading operations the transaction configuration readOnly
flag is set to true, all others are configured with a plain
@Transactional so that default transaction
configuration applies. For details see JavaDoc of
Repository. If you need to tweak transaction
configuration for one of the methods declared in
Repository simply redeclare the method in
your repository interface as follows:

Example 2.15. Custom transaction configuration for CRUD

public interface UserRepository extends JpaRepository<User, Long> {

  @Override
  @Transactional(timeout = 10)
  public List<User> findAll();

  // Further query method declarations
}

This will cause the findAll() method to
be executed with a timeout of 10 seconds and without the
readOnly flag.

 

Another possibility to alter transactional behaviour is using a
facade or service implementation that typically covers more than one
repository. Its purpose is to define transactional boundaries for non-CRUD
operations:

Example 2.16. Using a facade to define transactions for multiple repository
calls

@Service
class UserManagementImpl implements UserManagement {

  private final UserRepository userRepository;
  private final RoleRepository roleRepository;

  @Autowired
  public UserManagementImpl(UserRepository userRepository,
    RoleRepository roleRepository) {
    this.userRepository = userRepository;
    this.roleRepository = roleRepository;
  }

  @Transactional
  public void addRoleToAllUsers(String roleName) {

    Role role = roleRepository.findByName(roleName);

    for (User user : userRepository.findAll()) {
      user.addRole(role);
      userRepository.save(user);
    }
}

This will cause call to
addRoleToAllUsers(…) to run inside a
transaction (participating in an existing one or create a new one if
none already running). The transaction configuration at the repositories
will be neglected then as the outer transaction configuration determines
the actual one used. Note that you will have to activate
<tx:annotation-driven /> explicitly to get annotation
based configuration at facades working. The example above assumes you
are using component scanning.

 

2.4.1. Transactional query methods

To allow your query methods to be transactional simply use
@Transactional at the repository
interface you define.

Example 2.17. Using @Transactional at query methods

@Transactional(readOnly = true)
public interface UserRepository extends JpaRepository<User, Long> {

  List<User> findByLastname(String lastname);

  @Modifying
  @Transactional
  @Query("delete from User u where u.active = false")
  void deleteInactiveUsers();
}

Typically you will want the readOnly flag set to
true as most of the query methods will only read data. In contrast to
that deleteInactiveUsers() makes use of the
@Modifying annotation and overrides the
transaction configuration. Thus the method will be executed with
readOnly flag set to false.

 

[Note] Note
It’s definitely reasonable to use transactions for read only
queries and we can mark them as such by setting the
readOnly flag. This will not, however, act as check that
you do not trigger a manipulating query (although some databases
reject INSERT and UPDATE
statements inside a read only transaction). The readOnly
flag instead is propagated as hint to the underlying JDBC driver for
performance optimizations. Furthermore, Spring will perform some
optimizations on the underlying JPA provider. E.g. when used with
Hibernate the flush mode is set to NEVER when you
configure a transaction as readOnly which causes
Hibernate to skip dirty checks (a noticeable improvement on large
object trees).

2.5. Locking

To specify the lock mode to be used the
@Lock annotation can be used on query
methods:

Example 2.18. Defining lock metadata on query methods

interface UserRepository extends Repository<User, Long> {

  // Plain query method
  @Lock(LockModeType.READ)
  List<User> findByLastname(String lastname);
}

 

This method declaration will cause the query being triggered to be
equipped with the LockModeType
READ. You can also define locking for CRUD methods by
redeclaring them in your repository interface and adding the
@Lock annotation:

Example 2.19. Defining lock metadata on CRUD methods

interface UserRepository extends Repository<User, Long> {

  // Redeclaration of a CRUD method
  @Lock(LockModeType.READ);
  List<User> findAll();
}

 

2.6. Auditing

Most applications will require some form of auditability to track
when an entity was created or modified and by whom. Spring Data JPA
provides facilities to add this audit information to an entity
transparently by AOP means. To take part in this functionality your domain
classes must implement a more advanced interface:

Example 2.20. Auditable interface

public interface Auditable<U, ID extends Serializable>
        extends Persistable<ID> {

    U getCreatedBy();

    void setCreatedBy(U createdBy);

    DateTime getCreatedDate();

    void setCreated(Date creationDate);

    U getLastModifiedBy();

    void setLastModifiedBy(U lastModifiedBy);

    DateTime getLastModifiedDate();

    void setLastModified(Date lastModifiedDate);
}

 

As you can see the modifying entity itself only has to be an entity.
Mostly this will be some sort of User entity, so we chose U as parameter
type.

[Note] Note
To minimize boilerplate code Spring Data JPA offers
AbstractPersistable and
AbstractAuditable base classes that implement and
pre-configure entities. Thus you can decide to only implement the
interface or enjoy more sophisticated support by extending the base
class.

General auditing configuration

Spring Data JPA ships with an entity listener that can be used to
trigger capturing auditing information. So first you have to register
the AuditingEntityListener inside your
orm.xml to be used for all entities in your
persistence contexts:

Example 2.21. Auditing configuration orm.xml

<persistence-unit-metadata>
  <persistence-unit-defaults>
    <entity-listeners>
      <entity-listener class="….data.jpa.domain.support.AuditingEntityListener" />
    </entity-listeners>
  </persistence-unit-defaults>
</persistence-unit-metadata>

 

Now activating auditing functionality is just a matter of adding
the Spring Data JPA auditing namespace element to
your configuration:

Example 2.22. Activating auditing in the Spring configuration

<jpa:auditing auditor-aware-ref="yourAuditorAwareBean" />

 

As you can see you have to provide a bean that implements the
AuditorAware interface which looks as
follows:

Example 2.23. AuditorAware interface

public interface AuditorAware<T, ID extends Serializable> {

    T getCurrentAuditor();
}

 

Usually you will have some kind of authentication component in
your application that tracks the user currently working with the system.
This component should be AuditorAware and
thus allow seamless tracking of the auditor.

2.7. Miscellaneous

2.7.1. Merging persistence units

Spring supports having multiple persistence units out of the box.
Sometimes, however, you might want to modularize your application but
still make sure that all these modules run inside a single persistence
unit at runtime. To do so Spring Data JPA offers a
PersistenceUnitManager implementation that automatically
merges persistence units based on their name.

Example 2.24. Using MergingPersistenceUnitmanager

<bean class="….LocalContainerEntityManagerFactoryBean">
  <property name="persistenceUnitManager">
    <bean class="….MergingPersistenceUnitManager" />
  </property
</bean>

 

2.7.2. Classpath scanning for @Entity classes and JPA mapping
files

A plain JPA setup requires all annotation mapped entity classes
listed in orm.xml. Same applies to XML mapping
files. Spring Data JPA provides a
ClasspathScanningPersistenceUnitPostProcessor
that gets a base package configured and optionally takes a mapping
filename pattern. It will then scan the given package for classes
annotated with @Entity or
@MappedSuperclass and also loads the
configuration files matching the filename pattern and hands them to the
JPA configuration. The PostProcessor has to be configured like
this

Example 2.25. Using ClasspathScanningPersistenceUnitPostProcessor

<bean class="….LocalContainerEntityManagerFactoryBean">
  <property name="persistenceUnitPostProcessors">
    <list>
      <bean class="org.springframework.data.jpa.support.ClasspathScanningPersistenceUnitPostProcessor">
        <constructor-arg value="com.acme.domain" />
        <property name="mappingFileNamePattern" value="**/*Mapping.xml" />
      </bean>
    </list>
  </property>
</bean>

 

[Note] Note
As of Spring 3.1 a package to scan can be configured on the
LocalContainerEntityManagerFactoryBean directly
to enable classpath scanning for entity classes. See the JavaDoc
for details.

2.7.3. CDI integration

Instances of the repository interfaces are usually created by a
container, which Spring is the most natural choice when working with
Spring Data. There’s sophisticated support to easily set up Spring to
create bean instances documented in Section 1.3.3, “Creating repository instances”. As of version 1.1.0 Spring
Data JPA ships with a custom CDI extension that allows using the
repository abstraction in CDI environments. The extension is part of the
JAR so all you need to do to activate it is dropping the Spring Data JPA
JAR into your classpath.

You can now set up the infrastructure by implementing a CDI
Producer for the
EntityManagerFactory:

class EntityManagerFactoryProducer {

  @Produces
  @ApplicationScoped
  public EntityManagerFactory createEntityManagerFactory() {
    return Persistence.createEntityManagerFactory("my-presistence-unit");
  }

  public void close(@Disposes EntityManagerFactory entityManagerFactory) {
    entityManagerFactory.close();
  }
}

The Spring Data JPA CDI extension will pick up all
EntityManagers availables as CDI beans
and create a proxy for a Spring Data repository whenever an bean of a
repository type is requested by the container. Thus obtaining an
instance of a Spring Data repository is a matter of declaring an
@Injected property:

class RepositoryClient {

  @Inject
  PersonRepository repository;

  public void businessMethod() {

    List<Person> people = repository.findAll();
  }
}

Part II. Appendix

Appendix A. Namespace reference

A.1. The <repositories /> element

The <repositories /> triggers the setup of the
Spring Data repository infrastructure. The most important attribute is
base-package which defines the package to scan for Spring
Data repository interfaces.[2]

Table A.1. Attributes

Name Description
base-package Defines the package to be used to be scanned for repository
interfaces extending *Repository
(actual interface is determined by specific Spring Data module) in
auto detection mode. All packages below the configured package
will be scanned, too. Wildcards are also allowed.
repository-impl-postfix Defines the postfix to autodetect custom repository
implementations. Classes whose names end with the configured
postfix will be considered as candidates. Defaults to
Impl.
query-lookup-strategy Determines the strategy to be used to create finder
queries. See Section 1.3.2.1, “Query lookup strategies” for
details. Defaults to create-if-not-found.

 

Appendix B. Repository query keywords

B.1. Supported query keywords

The following table lists the keywords generally supported by the
Spring data repository query derivation mechanism. However consult the
store specific documentation for the exact list of supported keywords as
some of the ones listed here might not be supported in a particular
store.

Table B.1. Query keywords

Logical keyword Keyword expressions
AFTER After,
IsAfter
BEFORE Before,
IsBefore
CONTAINING Containing,
IsContaining,
Contains
BETWEEN Between,
IsBetween
ENDING_WITH EndingWith,
IsEndingWith,
EndsWith
EXISTS Exists
FALSE False,
IsFalse
GREATER_THAN GreaterThan,
IsGreaterThan
GREATER_THAN_EQUALS GreaterThanEqual,
IsGreaterThanEqual
IN In, IsIn
IS Is, Equals, (or no
keyword)
IS_NOT_NULL NotNull,
IsNotNull
IS_NULL Null, IsNull
LESS_THAN LessThan,
IsLessThan
LESS_THAN_EQUAL LessThanEqual,
IsLessThanEqual
LIKE Like, IsLike
NEAR Near, IsNear
NOT Not, IsNot
NOT_IN NotIn,
IsNotIn
NOT_LIKE NotLike,
IsNotLike
REGEX Regex, MatchesRegex,
Matches
STARTING_WITH StartingWith,
IsStartingWith,
StartsWith
TRUE True, IsTrue
WITHIN Within,
IsWithin

 

Appendix C. Frequently asked questions

C.1. Common

C.1.1. I’d like to get more detailed logging information on what
methods are called inside
JpaRepository, e.g. How can I gain
them?
You can make use of
CustomizableTraceInterceptor provided by
Spring:

<bean id="customizableTraceInterceptor" class="
  org.springframework.aop.interceptor.CustomizableTraceInterceptor">
  <property name="enterMessage" value="Entering $[methodName]($[arguments])"/>
  <property name="exitMessage" value="Leaving $[methodName](): $[returnValue]"/>
</bean>

<aop:config>
  <aop:advisor advice-ref="customizableTraceInterceptor"
    pointcut="execution(public * org.springframework.data.jpa.repository.JpaRepository+.*(..))"/>
</aop:config>

C.2. Infrastructure

C.2.1. Currently I have implemented a repository layer based on
HibernateDaoSupport. I create a
SessionFactory by using Spring’s
AnnotationSessionFactoryBean. How do I get
Spring Data repositories working in this environment?
You have to replace
AnnotationSessionFactoryBean with the
LocalContainerEntityManagerFactoryBean.
Supposed you have registered it under
entityManagerFactory you can reference it in you
repositories based on HibernateDaoSupport as
follows:

Example C.1. Looking up a SessionFactory from an
HibernateEntityManagerFactory

<bean class="com.acme.YourDaoBasedOnHibernateDaoSupport">
  <property name="sessionFactory">
    <bean factory-bean="entityManagerFactory" factory-method="getSessionFactory" />
  </property>
</bean>

 

C.3. Auditing

C.3.1. I want to use Spring Data JPA auditing capabilities but have
my database already set up to set modification and creation date on
entities. How to prevent Spring Data from setting the date
programmatically.
Just use the set-dates attribute of the
auditing namespace element to false.

Glossary

A

AOP
Aspect oriented programming

C

Commons DBCP
Commons DataBase Connection Pools – Library of the Apache
foundation offering pooling implementations of the
DataSource interface.
CRUD
Create, Read, Update, Delete – Basic persistence
operations

D

DAO
Data Access Object – Pattern to separate persisting logic from
the object to be persisted
Dependency Injection
Pattern to hand a component’s dependency to the component from
outside, freeing the component to lookup the dependant itself. For
more information see http://en.wikipedia.org/wiki/Dependency_Injection.

E

EclipseLink
Object relational mapper implementing JPA – http://www.eclipselink.org

H

Hibernate
Object relational mapper implementing JPA – http://www.hibernate.org

J

JPA
Java Persistence Api

S

Spring
Java application framework – http://www.springframework.org

Hibernate


Object/Relational Mapping


Hibernate ORM enables developers to more easily write applications whose data outlives the application process. As an Object/Relational Mapping (ORM) framework, Hibernate is concerned with data persistence as it applies to relational databases (via JDBC).
Unfamiliar with the notion of ORM? Read here.

JPA Provider

In addition to its own “native” API, Hibernate is also an implementation of the Java Persistence API (JPA) specification. As such, it can be easily used in any environment supporting JPA including Java SE applications, Java EE application servers, Enterprise OSGi containers, etc.

Idiomatic persistence

Hibernate enables you to develop persistent classes following natural Object-oriented idioms including inheritance, polymorphism, association, composition, and the Java collections framework. Hibernate requires no interfaces or base classes for persistent classes and enables any class or data structure to be persistent.

High Performance

Hibernate supports lazy initialization, numerous fetching strategies and optimistic locking with automatic versioning and time stamping. Hibernate requires no special database tables or fields and generates much of the SQL at system initialization time instead of at runtime.

Hibernate consistently offers superior performance over straight JDBC code, both in terms of developer productivity and runtime performance.

Scalability

Hibernate was designed to work in an application server cluster and deliver a highly scalable architecture. Hibernate scales well in any environment: Use it to drive your in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands.

Reliable

Hibernate is well known for its excellent stability and quality, proven by the acceptance and use by tens of thousands of Java developers.

Extensibility

Hibernate is highly configurable and extensible.

 

Projects

Guides and such

Getting Started Guide  A quickstart-style guide with tutorials. See also the Obtaining Hibernate section discussing the Hibernate artifacts and how to obtain them.

Migration Guide  Migration guide covering migration to 5.3 from the previous version

User Guide  Guide covering most user facing concepts and APIs of Hibernate

Integrations GuideGuide covering topics of interest for developers looking to develop integrations with Hibernate.

Hibernate JavaDocThe Hibernate JavaDocsWildFly, updating inGuide to update WildFly 11 to use the latest version of Hibernate ORM 5.3JPA 2.2 JavaDocThe JPA (2.2) JavaDocsFAQThe FAQJBoss-hosted wikiWiki (older content) hosted at JBoss.orgGitHub-hosted wikiWiki hosted at GitHub

Presentations

Brett did a few interesting presentations available on Slideshare:

If you are interested in Hibernate Performance Tuning, check out Vlad’s presentation:

Interface in Java

Interfejs u Javi je nacrt (blueprint) klase. On ima samo statičke konstante i apstraktne metode. Interfejs u javi je mehanizam za postizanje potpune apstrakcije. U Java interfejsu mogu postojati samo apstraktni metodi bez tela metoda. On se koristi za postizanje pune apstrakcije i višestrukog nasleđivanja u Javi. Java Interfejs takođe predstavlja IS-A relaciju. On ne može biti instanciran kao ni apstraktna klasa. Zašto se koristi interfejs? Postoje uglavnom tri razloga za upotrebu interfejsa. To su:
  • Koristi se za postizanje pune apstrakcije.
  • Pomoću interfejsa, moguće je podržati funkcionalnost višestrukog nasleđivanja.
  • Može se koristiti za postizanje tzv. labavog spajanja (loose coupling).
Napomena 1: Java kompajler dodaje ključne reči public i abstract pre metoda interfejsa i ključne reči public, static i final pre podataka-članova. Drugim rečima, polja interfejsa su public, static i final po default-u, a metodi su public i abstract.

Razumevanje odnosa između klasa i interfejsa Kao što je prikazano na sledećoj slici, klasa nasleđuje drugu klasu, interfejs nasleđuje drugi interfejs ali klasa implementira interfejs.

Jednostavan primer Java interfejsa U ovom primeru, interfejs Printable ima samo jedan metod, njegova implementacija je obezbeđena u klasi A.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface printable{ 
void print(); 
  
class A6 implements printable{ 
public void print(){System.out.println("Hello");} 
  
public static void main(String args[]){ 
A6 obj = new A6(); 
obj.print(); 
 
}
Ispis na ekranu:
Hello

Višestruko nasleđivanje u Javi pomoću interfejsa Ako klasa implementira više interfejsa, ili interfejs nasleđuje više interfejsa to je poznato kao višestruko nasleđivanje (multiple inheritance).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
interface Printable{ 
void print(); 
  
interface Showable{ 
void show(); 
  
class A7 implements Printable,Showable{ 
  
public void print(){System.out.println("Hello");} 
public void show(){System.out.println("Welcome");} 
  
public static void main(String args[]){ 
A7 obj = new A7(); 
obj.print(); 
obj.show(); 
 
}
Ispis na ekranu:
Hello
Welcome
Zašto višestruko nasleđivanje nije podržano preko klasa u Javi ali je moguće pomoću interfejsa?
Kao što je rečeno u poglavlju o nasleđivanju, višestruko nasleđivanje nije podržano u slučaju klasa. Međutim, podržano je u slučaju interfejsa zato što nema dvosmislenosti jer je implementacija obezbeđena preko implementacione klase. Na primer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface Printable{ 
void print(); 
  
interface Showable{ 
void print(); 
  
class testinterface1 implements Printable,Showable{ 
  
public void print(){System.out.println("Hello");} 
  
public static void main(String args[]){ 
testinterface1 obj = new testinterface1(); 
obj.print(); 
 
}
Ispis na ekranu:
Hello
Kao što se može videti u ovom primeru, Printable i Showable interfejs imaju iste metode ali njihovu implementaciju obezbeđuje klasa A, tako da nema dvosmislenosti. Nasleđivanje interfejsa Klasa implementira interfejs ali jedan interfejs nasleđuje drugi interfejs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
interface Printable{ 
void print(); 
interface Showable extends Printable{ 
void show(); 
class Testinterface2 implements Showable{   
public void print(){System.out.println("Hello");} 
public void show(){System.out.println("Welcome");} 
  
public static void main(String args[]){ 
Testinterface2 obj = new Testinterface2(); 
obj.print(); 
obj.show(); 
 
}
Ispis na ekranu:
Hello
Welcome
Šta je marker ili tagovani interfejs? Interfejs koji nema članova je poznat kao marker ili tagovani interfejs. Na primer: Serializable, Cloneable, Remote itd. Oni se koriste da obezbede neke suštinske informacije za JVM tako da JVM može izvoditi neke korisne operacije.
1
2
3
// Kako je napisan interfejs Serializable? 
public interface Serializable{ 
}
Ugnježđeni (nested) interfejs u Javi Napomena 2: Jedan interfejs može imati drugi interfejs i to je poznato kao ugnježđeni interfejs. Na primer:
1
2
3
4
5
6
interface printable{ 
 void print(); 
 interface MessagePrintable{ 
   void msg(); 
 
}

REST vs CRUD: Koja je razlika?

Some of the confusion around REST and CRUD has to do with the overlapping of basic commands mandated by both processes. This is further amplified by the Rails community embracing REST and its GET, PUT, POST nature.

Savvy developers can see glaring similarities between GET, PUT, POST and CREATE, READ, UPDATE, DELETE. The latter commands are the foundation of CRUD. And while the similarities cannot be ignored, it should be noted that REST is not simply a carbon copy of CRUD.

REST: Foundation and Principles

Each REST command is centered around a resource. In REST, a resource is really anything that can be pointed to via HTTP protocol. For example, an image, a website, a document or a weather service. The possibilities are almost endless.

In plain terms, REST stands for Representational State Transfer, an architectural style designed for distributed hypermedia, or an Application Programming Interface. You’ve probably heard the latter referred to as an API. Another way to think of an API is to define it as a web service that conforms to the architectural principles of REST. Each API is called by issuing a standard HTTP request method: POST, GET, PUT and less commonly, DELETE. DELETE is usually implied, though not necessarily stated.

The terms that define REST principles were introduced in Dr. Roy Fieldings’ thesis, “Architectural Styles and the Design of Network-Based Software Infrastructure.” Overall, REST can be thought of as the standard in service application development. It offers an alternative to Simple Object Access Protocol (SOAP), COBRA, RMI and many others.

Principles of REST

There are six guiding constraints of REST. These are:

Client-Server Mandate

This mandate underscores the fact that REST is a distributed approach via the nature of separation between client and server. Each service has multiple capabilities and listens for requests. Requests are made by a consumer and accepted or rejected by the server.

Statelessness

Due to the nature of statelessness, it is a guiding principle of RESTful architecture. It mandates what kind of commands can be offered between client and server. Implementing stateless requests means the communication between consumer and service is initiated by the request, and the request contains all the information necessary for the server to respond.

Cache

Cache mandates that server responses be labeled as either cacheable or not. Caching helps to mitigate some of the constraints of statelessness. For example, a request that is cached by the consumer in an attempt to avoid re-submitting the same request twice.

Interface / Uniform Contract

RESTful architecture follows the principles that define a Uniform Contract. This prohibits the use of multiple, self-contained interfaces within an API. Instead, one interface is distributed by hypermedia connections.

Layered System

This principle is the one that makes RESTful architecture so scalable. In a Layered System, multiple layers are used to grow and expand the interface. None of the layers can see into the other.

This allows for new commands and middleware to be added without impacting the original commands and functioning between client and server.

Optional: Code-On-Demand

RESTful applications don’t have to include Code-On-Demand, but they must have Client-Server, Statelessness, Caching, Uniform Contract and Layered Systems. Code-on-Demand allows logic within clients to be separate from that within servers. This allows them to be updated independently of server logic.

REST: In a Nutshell

REST refers to a set of defining principles for developing API. It uses HTTP protocols like GET, PUT, POST to link resources to actions within a client-server relationship. In addition to the client-server mandate, it has several other defining constraints. The principles of RESTful architecture serve to create a stable and reliable application, that offers simplicity and end-user satisfaction.

CRUD: Foundation and Principles

With a better understanding of RESTful architecture, it’s time to dive into CRUD.

CRUD is an acronym for CREATE, READ, UPDATE, DELETE. These form the standard database commands that are the foundation of CRUD.

Many software developers view these commands as primitive guidance, at best. That’s because CRUD was not developed as a modern way to create API. In fact, CRUD’s origins are in database records.

By definition, CRUD is more of a cycle than an architectural system. On any dynamic website, there are likely multiple CRUD cycles that exist.

For instance, a buyer on an eCommerce site can CREATE an account, UPDATE account information and DELETE things from a shopping cart.

A Warehouse Operations Manager using the same site can CREATE shipping records, RETRIEVE them as needed and UPDATE supply lists. Retrieve is sometimes substituted for READ in the CRUD cycle.

Database Origins

The CRUD cycle is designed as a method of functions for enhancing persistent storage, for instance with a database of records. As the name suggests, persistent storage outlives the processes that created it. These functions embody all the hallmarks of a relational database application.

In modern software development, CRUD has transcended its origins as foundational functions of a database and now maps itself to design principles for dynamic applications like HTTP protocol, DDS and SQL.

Principles of CRUD

As mentioned above, the principles of the CRUD cycle are defined as CREATE, READ/RETRIEVE, UPDATE and DELETE.

Create

CREATE procedures generate new records via INSERT statements.

Read/Retrieve

READ procedures reads the data based on input parameters. Similarly, RETRIEVE procedures grab records based on input parameters.

Update

UPDATE procedures modify records without overwriting them.

Delete

DELETE procedures delete where specified.

REST and CRUD Similarities

If you look at the two as we have described above, it may be difficult to understand why they are often treated in the same way. REST is a robust API architecture and CRUD is a cycle for keeping records current and permanent.

The lack of clarity between the two is lost for many when they fail to determine when CRUD ends and REST begins. We mentioned above that CRUD can be mapped to DDS, SQL and HTTP protocols. And that HTTP protocols are the link between resources in RESTful architecture, a core piece of REST’s foundation.

Mapping CRUD principles to REST means understanding that GET, PUT, POST and CREATE, READ, UPDATE, DELETE have striking similarities because the former grouping applies the principles of the latter.

However, it is also important to note that a RESTful piece of software architecture means more than mapping GET, PUT, POST commands.

REST and CRUD: What’s the Difference?

CRUD is a cycle that can be mapped to REST, by design. Permanence, as defined in the context of CRUD, is a smart way for applications to mitigate operational commands between clients and services.

But REST governs much more than permanence within its principles of architecture. Here are some of the ways that REST is not only different than CRUD but also offers much more.

  • REST is an architectural system centered around resources and hypermedia, via HTTP protocols
  • CRUD is a cycle meant for maintaining permanent records in a database setting
  • CRUD principles are mapped to REST commands to comply with the goals of RESTful architecture

In REST:

  • Representations must be uniform with regard to resources
  • Hypermedia represents relationships between resources
  • Only one entry into an API to create one self-contained interface, then hyperlink to create relationships

The Way Forward

Developers select REST for a number of reasons.

  1. Performance
  2. Scalability
  3. Simplicity
  4. Modifiability
  5. Visibility
  6. Portability
  7. Reliability

Not surprisingly, the demand for RESTful architecture has continued to grow over the years. And, as it becomes an even more popular architectural style, developers should be able to make the distinction between the principles of other options like SOAP, COBRA and RMI.

Introducing Cognitive Service Management

Cognitive Service Management is the cutting-edge of ITSM. This innovative approach helps businesses keep up with the pace of emerging technologies and diverse environments. Download the whitepaper to learn more.
Download Whitepaper ›

Spring IDE and the Spring Tool Suite – Using Spring in Eclipse

This article is an introduction to Spring IDE and the Spring Tool Suite – a set of plugins to simplify the development of Spring-based applications in Eclipse. Let’s start by looking at the Spring Framework and how we can use it to write a few simple Spring applications.

Spring in a Nutshell

For a concise introduction to Spring, read the reference documentation for Spring 4. It contains a nice introduction to the core concepts as well as a comprehensive overview and in-depth look at all of the various features that come with the latest version of the Spring core framework. In addition to the core framework, the Spring IO platform documentation gives you an additional overview about how to use both the execution layer and the foundation layer components to build modern enterprise applications.

In the simplest terms, Spring allows you to build an application using Plain Old Java Objects (POJO’s) and dependency injection, which helps you wire up the different components of your application. Most people prefer to use annotations, or Java Configuration and therefore stay on the pure Java side. You can also use an XML configuration file to ‘wire up’ your POJOs that act as beans. All of these methods are perfectly fine and supported by Spring.

The components that you define, the Spring beans, can then reside in the Spring container. In addition to the pure dependency injection mechanism, Spring provides a first-class integration for aspect-oriented programming (AOP) and comes with a huge set of service-level abstractions. Those are ready-to-use bean implementations that encapsulate certain technologies like transactions, persistence technologies, and many more. All this results in a programming model that lets you write your application independent of a concrete technology or a concrete runtime environment for deployment. This is why, many years after its release, Spring probably the most popular framework and environment for implementing Java enterprise applications.

Spring IDE (Eclipse Plug-in)

The Spring IDE is an open-source project that provides a set of plugins for the Eclipse IDE. These plugins make the Eclipse IDE Spring-aware. After installing the Spring IDE plugins, your IDE understands your projects from the perspective of the Spring framework and provides you with a wide variety of additional features that make it easier and more convenient to work with Spring projects in Eclipse.

The IDE provides various wizards for creating Spring projects and getting started with Spring if you’re a beginner. Of course, it can also be used on existing Spring projects. Once you have a project configured to be a Spring project, you can let the IDE know which Spring configuration files your projects uses (either those XML config files or your Spring JavaConfig classes that use the @Configuration annotation). From there on, you can benefit from the Spring-specific tooling support, including:

Spring-specific content-assist and validation for your spring config files
Spring-specific refactoring support for your spring config files
Graphical visualization of your beans and their dependencies
Graphical diagram-like editors for Spring Integration, Spring Batch, and Spring Webflow
Advanced support for Spring aspects including pointcut visualization and navigation
Integration with AJDT and Eclipse Mylyn tooling
Support for Spring bean profiles and validation inside profiles
Direct integration of the ‘getting started’ guides from http://spring.io/guides
A number of example and reference applications to learn from
Support for creating and using Spring Boot projects right within your IDE
and more…

The Spring Tool Suite (Full Distribution)

While the Spring IDE project provides a set of plugins for the Eclipse IDE, the Spring Tool Suite comes as a ready-to-use distribution of the latest Eclipse releases with the Spring IDE components pre-installed. This includes the tc Server integration for Eclipse (another IDE extension that is provided by Pivotal as an open-source project) and various other additions to Eclipse that turn the pure Eclipse IDE into a ready-to-use, best-of-breed environment for enterprise Spring application development. To download the Spring Tool Suite, go to: http://spring.io/tools

Lets get Started – Installing the Spring Tooling

There are two ways to get Spring-tooling enabled in Eclipse: Either you download the Spring Tool Suite distribution as a ready-to-use package (recommended) or you download the latest Eclipse JEE package from http://www.eclipse.org/ and start from there. You might also have an existing Eclipse IDE running on your machine that you just want to extend with the Spring tooling. The easiest way to install the Spring tooling into your existing (or freshly downloaded) Eclipse IDE is to go the Eclipse Marketplace and search for the “Spring Tool Suite” – and install from there.

If you would like to use Maven (which is used in many Spring projects) and you haven’t installed the Maven Integration for Eclipse yet, you should go ahead and do that. You can grab it from the Eclipse Marketplace or directly from the main Eclipse update repository, which is pre-configured in your Eclipse IDE. Just look for the “Install New Software” wizard. It is also recommended that you install the Maven Integration for Eclipse WTP, which makes it easy to work with web projects using Maven inside Eclipse. If you decided to download the Spring Tool Suite distribution package, those extensions are already pre-installed for you.

Create a New Project

To create a new project, you just need to use the New Spring Project wizard to get going. If you don’t do this, it’s ok – you can just add a “Spring Nature” to your project at a later stage.

The wizard provides you with a few options for getting started with a new Spring project. For some of the common use cases, the Spring tooling provides a number of templates, like a simple Spring MVC application or some examples for using Spring Integration, just to name a few. After giving the project a name and selecting the template, the wizard usually allows you to customize a few settings in the project (like the package names). Once that’s done, you are ready to go. This is an easy way to get started with a ready-to-use Spring project that already runs and does something for you.

The simple Spring MVC project example is a very popular one that gets you started with a more classic Spring web application, which includes:

Traditional Spring XML configurations for the web application
Component scanning for the controller implementations that use the @RequestMapping annotation in the source code
A traditional JSP page for the frontend, which is probably similar to the structure of many existing Spring web applications

If you are using the Spring Tool Suite distribution, you get a ready-to-use tc Server instance created and configured in your workspace. It allows you, for example, to deploy and run your freshly created Spring MVC app immediately.

If you would like to start with an empty project instead, you can do that, of course. For this case, there are a few simple templates provided by the wizard that help you do that. If you choose to use Maven for your project build and dependency management, you could choose the simple Maven web template. It doesn’t create any code for you, but it puts all the necessary Spring libraries on the classpath of the project.

If you started with the Spring MVC web application example, some of the features of the Spring tooling will immediately catch your eye. The project explorer gets a new section “Spring”, that shows you the structure and the beans of your Spring applications. Furthermore, it gives you an overview of the annotation-based stereotypes used within your project. In web applications, for example, it gives you a nice overview of the defined @RequestMapping methods with the ability to jump right into the code.

Next Page: Using Spring Boot and the new Getting Started Guides

Using Spring Boot and the new Getting Started Guides

If you’ve seen the new Spring Boot project, then you know how easy it is to get started with Spring using Spring Boot. There is a direct integration for that in the tooling starting in version 3.4.0. You can go ahead and create a new Spring Boot project by selecting the “New -> Spring Started Project”. It will open a simple wizard for you that lets you choose among various options for what to get on the classpath of the new Spring project and it creates a simple main Application class that you could use to startup the application.

Since Spring Boot takes care of starting up an embedded Tomcat instance, you don’t have to deploy your application to a server that you configured inside your IDE anymore. Simply starting the project as a general Java application will work just fine.

In addition to using the very basic (and purist) Spring Boot approach, you could also use the new Getting Started Guides (http://spring.io/guides) directly from within the tooling. To do that, you select the “New -> Import Spring Getting Started Content” wizard and go from there. It lists all the available guides that you can find on the http://spring.io website and lets you import them into your IDE quickly (alongside the documentation inside the IDE using a browser view). This provides you with a nice learning experience when getting started with Spring in general or when diving into certain features of Spring.

Configuring an Existing Project

If you are already a Spring developer and want to benefit from the Spring tooling in your IDE, you will want to enable the tooling for any existing projects in your workspace. Just select your project, open the context menu, and select “Spring Tools -> Add Spring Project Nature”. Once you’ve done that, the IDE treats this project as a Spring project and enables all the Spring-related features for it.

Once the project in Eclipse or the Spring Tool Suite has the Spring nature enabled, you can go ahead and configure the used Spring bean config files. To do that you just go to the project preferences and select “Spring -> Beans Support”.

There you can configure the Spring config files (either the Spring XML config files or the @Configuration classes if you are using the pure annotation-based method). This lets the tooling know about your config files and tells the tools where to start the Spring-specific analysis of your project.

Some of those config files are recognized and configured automatically, since the tooling knows about the usual names and the usual locations for those files (especially for web apps). If they are not showing up automatically, please go ahead and configure them manually (and probably file a bug with the Spring IDE developers to let them improve the automatic discovery of those config files).

Working with the Spring Tooling

The tooling is what makes working with Spring in Eclipse a real pleasure. The Spring explorer view and the corresponding section of the project explorer give you a nice overview of your Spring project, and every time you change your code or your config files, it gets updated. It allows you to quickly navigate to the source code and helps you quickly understand the structure of your Spring project.

The most valuable aspect of the tooling is the support for editing and validating Spring configurations. It doesn’t matter if you use Spring XML config files or if you prefer the annotation-based configuration style. The tooling gives you meaningful content-assist all over the place and assists you with additional, Spring-specific validations that help you identify problems, typos, and other issues as early as possible.

The most comprehensive support is available for working with Spring XML config files. When defining Spring beans in the XML config files, you get content-assist for all kinds of elements, including full assist for typing in the class of a bean, referring to other bean definitions, or referring to a class property in order to inject dependencies.

If a problem appears, the tooling assists you in fixing this problem by providing quick-fix solutions. That makes it easy to add, for example, a missing bean definition or to create a new property in the related Java class, if the config file refers to a missing property.

Validations take care of checking your Spring config files and they make sure that you don’t forget a bean definition. They also points you toward the better options for writing your Spring configs if it detects a common anti-pattern. This is extremely useful for autowired dependencies where you don’t know right away what gets injected at runtime, or whether something exists at runtime that will be injected into an @Autowired field or parameter. The tooling can check this for you and give you a warning if it cannot find anything that could get injected there.

A list of the available validations can be found in the global preferences via “Preferences -> Spring -> Project Validators”. That preference page allows you to enable or disable those validations as well.

Refactoring

Improving the structure of your code is always on your mind if you’re a professional developer, and today’s IDE provide nice refactoring support for these tasks. The Spring tooling, for example, integrates the Spring-specific configuration files into this refactoring support of your IDE. Whenever you rename a class in Eclipse, it gets updated in your Spring config files as well. The same happens if you change the name of a property in your Java class. If there is a reference to this property in one of your Spring config files, it gets updated as well. In addition to that, it also allows you to rename beans themselves via a special “Rename Bean ID” refactoring, changing all references to that bean ID automatically.

Additional highlights

This article covers only the basic features and first steps for getting started with the Spring tooling for Eclipse. The tooling provides a lot more functionality than what is mentioned in this article. The graphical views and editors are especially powerful when working with Spring Integration, Spring Batch, and Spring Webflow. And there is more and more support emerging for annotation-based Spring configurations, although the general Java tooling in Eclipse is already extremely useful and supportive for those out-of-the-box.

If you want to learn more about the tooling and see what is new in the latest versions, please take a look at the new and noteworthy documentation that comes with every release:

More information can be found here:

Show Buttons
Hide Buttons