Understanding how to use Hibernate and Spring Data JPA.
This example demonstrates persistence with Hibernate and Spring Data JPA
-
Dependencies
⇒ pom.xml
There are new dependencies introduced. Look forspring-data-jpa
in thepom.xml
. -
Config - the class that specifies the component scanning instruction.
⇒ ColoredShapeConfig.java
The config class is supplied. This config class specifies the packages to be scanned for components.
⇒ HibernateJPAConfig.java
The class that configures the HibernateEntityManager to connect to a database. -
Controller layer
⇒ ColoredShapeControllingBean.java
The class auto-wires aColoredShapeService
interface, the Spring context has aColoredShapeServiceImpl
that will be used as an auto-wired instance (remember the Liskov Substitution Principle). The controller invokes the service methods to persist and retrieve ColoredShape instances. The class is marked with a@Component
annotation. -
Service layer
⇒ ColoredShapeServiceImpl.java
The class is marked with a@Service
annotation. The@Service
is an alias for the@Component
annotation (see the code). It should display a@AliasFor(annotation = Component.class)
. The service implementation auto-wires aColoredShapeDao
interface and will access theColoredShapeDaoImpl
via the spring context. Methods in the service delegate to methods in the DAO. -
DAO layer
⇒ ColoredShapeDao.java
Notice the magic that no implementation was coded. Spring Data JPA "figures out" the implementations from the method signature. The method signatures can get complex with AND and OR clauses. For instance, a valid method:findOneByColorOrShape(String color, String shape)
.
A new dependency spring-data-jpa is added. A Java configuration is used to setup the embedded database (XML could have been used as well).
The service layer invokes the DAO layer. The DAO layer is simply an interface that
extends the CrudRepository
from spring-data-jpa. CrudRepository
provides basic method
signatures for CRUD operations on a given entity.
-
What is the difference between Spring JPA and Spring Data JPA?
Prev | TOC | Next |
---|---|---|