Monday, June 23, 2014

Spring Data - JPA

Spring-Data project makes it easier to use data access technologies be it relational databases, NoSQL non-relational databases or other data services.  Spring-Data contains many sub-projects that are specific to a given data access technology, we will primarily look at spring Data JPA technology, which makes it easier to access JPA implementations.

Spring Data JPA project makes it easy to easily implement JPA based repositories. Using Spring Data JAP generally involves declaring repository interfaces which can include custom finder methods and leave it to Spring Data JPA to generate implementation automatically.

Core Interfaces:

Repository:
Repository is the central core interface when it comes to using Spring Data; not to be confused with the Repository annotation which has been in spring 2.0, The Repository interface is marker interface which captures the domain type to manage as well as the domain type's id type.

CRUDRepository:
The CRUDRepository interface extends the Repository interface and provides CRUD (Create Read Update and Delete) functionalities for the managed entity object. The CRUDRepository provides the following functionality:
  • Save - Saves and returns the entity which can be used further operations
  • findOne – Finds and returns an entity by its primary id
  • findAll – Returns list of all entities of the type
  • exists – Checks and returns boolean value for existence of the entity by  primary key        
  • count – Returns the count of number on entities available
  • delete – Deletes the entity
  • deleteAll – Deletes all the entities managed by the repository.

PagingAndSortingRepository:
The PagingAndSortingRepository extends the CRUDRepository and provides functionality for pagination and sorting.

JpaRepository:

The JPARepository extends the PagingAndSortingRepository to provide JPA specific extensions for the repository, Additional attributes to gain more detailed control over the setup of the repositories specifying EntityManager and TransactionManager references can be done via xml of through spring configuration object. 

Query Methods

Standard CRUD functionality usually has queries on the underlying data store and generally these may be mapped SQL statements or named queries, but with Spring-Data the underlying query can be generated automatically by the repository. The repository proxy has two ways to derive a store-specific query from the method name. It can derive the query from the method name directly, or by using a manually defined query depending upon following the Query lookup strategies.

CREATE - Construct a query from the query method name by removing given set of well-known prefixes from the method name and parse the rest of the method.

USE_DECLARED_QUERY – Will try to find a declared query and will throw an exception in case it can't find one. The query can be defined by an annotation somewhere or declared by other means.

CREATE_IF_NOT_FOUND – This is the default strategy that combines CREATE and USE_DECLARED_QUERY. It looks up a declared query first, and if no declared query is found, it creates a custom method name-based query.

The query look up mechanism strips prefixes find…By, read…By, query…By, count…By, and get…By from the method and starts parsing the rest of it.


Please refer to the Spring-Data reference for more details on query look up styles. 


@Query

Using named query in JPA is a very valid approach for annotating model objects and then referring to the named queries in the data access object, however with this approach the entity model soon becomes cluttered with named query and the DAO classes may get hard to read since you would be going back and forth between the actual query and the DAO class where it is used.  


The Spring-Data @Query annotation makes is very simple to annotate queries in the repository interface and use them in the repository itself, native queries easily supported by marking nativeQuery attribute as true. Named query parameters are also easily supported. 

Please refer to the Spring-Data reference for more details on @Query examples. 

Spring Data JPA Implementation:

Please refer to previous post if you plan to import the test project onto local machine and run code locally. 

Annotated Model Object: 
The com.malcolm.daotest.hibernate.model package contains JPA annotated model, which is pretty straight forward. We annotate each Java object with the @Entity,  @Table and @Column annotation at minimum. JPA annotations are found in the javax.persistence.* package.  Please refer here for declaring Object Relational Mapping in the POJO beans. 

Spring Data JPA Repository: 


The com.malcolm.daotest.hibernate.dao.spingdatajpaimpl.EmployeeInfoRepository is the JPA repository for the the Spring Data JPA implementation. The interface extends JpaRepository for Employee type and defines @Query methods. The reason we use  explicit @Query with JOIN FETCH strategy is to minimize n+1 issue with multiple calls to the database, we still have a issue since there are multiple collection based relationships and n+1 issue occurs, if we try to put a JOIN FETCH strategy for all collections we will get a Cartesian product.  



Spring Data JPA DAO Implementation: 

The com.malcolm.daotest.hibernate.dao.spingdatajpaimpl.EmployeeDAOHibernateSpringDataJPAImpl class provides Spring Data JPA implementation via the EmployeeInfoRepository.


Spring Data JPA Configuration: 

The com.malcolm.daotest.hibernate.HibernateDAOSpringDataJPAConfig sets up the required bean dependency setting the EntityManager and TransactionManager, the datasource and hibernate properties are configured in the BaseHibernateDAOConfig.

The DAO uses the @EnableJpaRepositories to scan packages of the annotated configuration class for Spring Data repositories and @ComponentScan annotations to clearly mark the annotated models and Service Components.


Spring Data Implementation Design: 


Strengths:
  1. Very flexible and concise approach of integrating with data services.  
  2. Smart findByxx methods that can be easily used without much coding. 
Weakness:
  1. The weakness will depend on the underlying data services, Spring Data JPA provides a concise wrapper for JPA data services.  
Please refer to Spring Data Reference for further details.  

Back to previous post on Object Relational Mapping.

Until next time,
Malcolm


No comments:

Post a Comment