Skip to content

Latest commit

 

History

History
81 lines (60 loc) · 3.68 KB

07_PersistenceWithSpringDataJPA.adoc

File metadata and controls

81 lines (60 loc) · 3.68 KB

Persistence with Spring Data JPA and Hibernate

Understanding how to use Hibernate and Spring Data JPA.

Persistence with Spring Data JPA - Configuration

This example demonstrates persistence with Hibernate and Spring Data JPA

  1. Dependencies
    pom.xml
    There are new dependencies introduced. Look for spring-data-jpa in the pom.xml.

  2. 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.

  3. Controller layer
    ColoredShapeControllingBean.java
    The class auto-wires a ColoredShapeService interface, the Spring context has a ColoredShapeServiceImpl 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.

  4. 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 a ColoredShapeDao interface and will access the ColoredShapeDaoImpl via the spring context. Methods in the service delegate to methods in the DAO.

  5. 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.

Quiz time

Quiz

  • What is the difference between Spring JPA and Spring Data JPA?


Prev TOC Next

Persistence with JPA

TOC