Spring Data JPA
In entire web application, the DAO layer usually consists of a lot of boilerplate code that can be simplified.
Benefits of simplification
Decrease in the number of artifacts that we need to define and maintain.
Consistency of data access patterns and consistency of configuration.
Spring Data JPA framework takes this simplification one step forward and makes it possible to remove the DAO implementations entirely. The interface of the DAO is now the only artifact that we need to explicitly define.
For this, a DAO interface needs to extend the JPA specific Repository interface
JpaRepository
or its super interfaceCrudRepository
. This will enable Spring Data to find this interface and automatically create an implementation for it.By extending the interface we get the most required CRUD methods for standard data access available in a standard DAO.
Crud Repository
org.springframework.data.repository.CrudRepository<T, ID>
methods are as follows,
Jpa Repository
org.springframework.data.jpa.repository.JpaRepository<T, ID>
Custom Access Method and Queries
By extending one of the Repository interfaces, the DAO will already have some basic
CRUD
methods (and queries) defined and implemented.To define more specific access methods, Spring JPA supports quite a few options:
When Spring Data creates a new Repository implementation, it analyses all the methods defined by the interfaces and tries to automatically generate queries from the method names. While this has some limitations, it’s a very powerful and elegant way of defining new custom access methods with very little effort.
Consider following examples,
findBy
,And
,Or
,Distinct
example queries.Limiting the result size of a query with Top and First.
Simply define a new method in the interface and provide the actual
JPQL
query by using theorg.springframework.data.jpa.repository.@Query
annotation. This methods is used to write custom query.
the
:
before arguments is use to specify named Parameters, which acts as place holder. Just like?
in jdbc.org.springframework.data.repository.query.@Param
is used to bind named parameters with query method param.
Transaction Configuration
The actual implementation of the Spring Data managed DAO layer is hidden since we don’t work with it directly.
JpaRepository
interface throughJpaRepositoryImplementation
interface is implemented by theorg.springframework.data.jpa.repository.support.SimpleJpaRepository<T, ID>
, which defines default transaction mechanism using annotations.The annotation used is
@Transacational
fromorg.springframework.transaction.annotation
.These tansaction can be easily overridden manually per method as well by supplying your own configurations.
Exception Translation
Exception translation is still enabled by the use of the
@Repository
annotation internally applied on the DAO implementation class.
Last updated