Skip to content

Latest commit

 

History

History
197 lines (142 loc) · 9.46 KB

05_PersistenceWithHibernate.adoc

File metadata and controls

197 lines (142 loc) · 9.46 KB

Persistence with Spring with Hibernate

Understanding how to use Hibernate for persistence in Spring.

Spring + Hibernate persistence - Overview

Only one sample discussed.

Tip
This section focuses on package naming and standards as well.
Important
System.out.println(…​) calls are replaced with a LOGGER instance.

Recommended packaging call hierarchy (the package layers as called from any code using the application): (controller → service → dao) + model + config is covered.

An embedded database is used, in lieu of an actual external database.

Output - Standards

  1. Usage of System.out.println(…​) is generally a bad idea. Not all applications run on servers that can be accessed while the application is running. Additionally, there may be a need to output to more than one location such as a database, email, file, message bus etc. Hence, the System.out.println(…​) calls are replaced with LOGGER usage.

Introduction to Hibernate

Covering a full course on Hibernate is definitely out of scope of this tutorial. A brief set of notes on Hibernate:

  • Hibernate ORM (Object Relational Mapping) is an object-relational mapping tool for the Java programming language.

  • Hibernate’s works by mapping Java classes to database tables and mapping from Java data types to SQL data types.

  • Hibernate ORM (Hibernate in short) works by mapping domain model objects with an annotation of @Entity. The domain model maps to a table with the annotation of @Table.

  • Hibernate also provides data query and retrieval facilities by generating SQL calls.

  • Mapping of Java classes to database tables is implemented by the configuration of an XML file or by using Java Annotations.

  • Hibernate provides a SessionFactory to manage database sessions and transactions.

  • Hibernate provides an EntityManagerFactory to manage database sessions and transactions using the Java Persistence API standard.

This chapter demonstrates using Hibernate-proprietary SessionFactory to persist to and retrieve from an embedded database.

Persistence with Hibernate - Configuration

This example demonstrates persistence with Hibernate.

  1. Hibernate dependencies
    pom.xml
    Look for spring-jdbc, spring-orm and hibernate-core. The embedded database is h2.

  2. Embedded H2 Database
    HibernateSessionConfig.java
    Check the getDataSource() method.

  3. External properties configuration
    HibernateSessionConfig.java
    Check the @PropertySource above the class name.

  4. External properties
    application.properties

  5. Loading external properties
    HibernateSessionConfig.java
    Check the getHibernateProperties() method.

  6. Transaction manager
    HibernateSessionConfig.java
    Check the getSessionFactory() method.

  7. Component scan
    ColoredShapeConfig.java
    The class is declared as @Configuration and specifies a @ComponentScan instruction against the base package.

Two new dependencies spring-orm and hibernate-core are added. A Java configuration is used to setup the embedded database (XML could have been used as well).

Hibernate is configured with external properties via a @PropertySource, pointing to an application.properties.

In addition to the embedded database and Hibernate configuration, a LocalSessionFactoryBean is configured to manage persistence for Hibernate via auto-wiring.

A TransactionManager is also created for saves and updates. This provides for a means to commit changes.

Persistence with Hibernate - Invocation

This example demonstrates persistence with Hibernate.

  1. Application - the executable to launch
    ColoredShapeApplication.java
    The example class loads the Spring context via an AnnotationConfigApplicationContext.

  2. Config layer - the configuration layer
    ColoredShapeConfig.java
    The config class is supplied. This config class specifies the packages to be scanned for components.
    HibernateSessionConfig.java
    The class sets up the Hibernate Session Factory bean to create a connection to the 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
    ColoredShapeDaoImpl.java
    The class is marked with a @Repository annotation. The @Repository annotation is an alias for the @Component annotation. It too should have a @AliasFor(annotation = Component.class). The DAO implementation uses an instance of the SessionFactory to communicate with the database. Similar to the service, the DAO interface is wired with an implementation via the Spring context.

  6. Model layer
    ColoredShape.java
    This is the model for ColoredShape. The id attribute maps to a primary key in the database table.

The application ColoredShapeApplication gets the bean for the controller ColoredShapeControllingBean. The controller creates two new shapes, adds and lists them. Additionally, the controller bean also updates one of the beans.

Each activity in the controller bean invokes the service layer. The service layer is used to aggregate calls from/to the database to produce java objects, that match the expected output. Since the example does not include complex objects, the service layer appears to be a pass through layer to the DAO.

The service layer invokes the DAO layer. The DAO layer wires in a SessionFactory, that is loaded by Spring as a part of its finding a Hibernate core dependency.

The transaction management is performed via the annotation @Transactional on the class or method. The DAO is declared as read-only at the class level (@Transactional(readOnly = true)) by default and as read-write with propagation (@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)) for the save method.

The model is marked as an @Entity and maps to a @Table(name = "COLORED_SHAPE").

Quiz time

Quiz

  • What is Hibernate’s core class for persistence?

  • What is the recommended package call hierarchy for an application?

  • What is the recommended way to emit output from a program?


Prev TOC Next

Persistence with JDBC

TOC

Persistence with JPA