Understanding how to use Hibernate for persistence in Spring.
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.
-
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, theSystem.out.println(…)
calls are replaced with LOGGER usage.-
Logging dependencies
⇒ pom.xml
Look forlogback-classic
andjcl-over-slf4j
. -
Logging configuration
⇒ logback.xml -
Logging use
⇒ ColoredShapeControllingBean.java
-
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.
This example demonstrates persistence with Hibernate.
-
Hibernate dependencies
⇒ pom.xml
Look forspring-jdbc
,spring-orm
andhibernate-core
. The embedded database ish2
. -
Embedded H2 Database
⇒ HibernateSessionConfig.java
Check thegetDataSource()
method. -
External properties configuration
⇒ HibernateSessionConfig.java
Check the@PropertySource
above the class name. -
External properties
⇒ application.properties -
Loading external properties
⇒ HibernateSessionConfig.java
Check thegetHibernateProperties()
method. -
Transaction manager
⇒ HibernateSessionConfig.java
Check thegetSessionFactory()
method. -
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.
This example demonstrates persistence with Hibernate.
-
Application - the executable to launch
⇒ ColoredShapeApplication.java
The example class loads the Spring context via anAnnotationConfigApplicationContext
. -
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. -
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
⇒ 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 theSessionFactory
to communicate with the database. Similar to the service, the DAO interface is wired with an implementation via the Spring context. -
Model layer
⇒ ColoredShape.java
This is the model for ColoredShape. Theid
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")
.
-
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 |
---|---|---|