Understanding how to use Hibernate and Spring with Java Persistence API.
This example demonstrates persistence with Hibernate.
-
Hibernate dependencies
⇒ pom.xml
Look forspring-jdbc
,spring-orm
,hibernate-core
andhibernate-entitymanager
dependencies. -
Application
⇒ ColoredShapeApplication.java
The class loads a Spring context through anAnnotationConfigApplicationContext
. -
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
⇒ 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.
A new dependency hibernate-entitymanager
is added. A Java configuration is used to setup the
embedded database (XML could have been used as well).
Hibernate itself, is configured with external properties via a @PropertySource
, pointing to
an application.properties
.
In addition to the embedded database and Hibernate configuration, a
LocalContainerEntityManagerFactoryBean
is configured to manage persistence for Hibernate.
The service layer invokes the DAO layer. The DAO layer declares an EntityManager
, as
a @PersistenceContext
.
The transaction management is performed via the annotation @Transactional
. The DAO is declared
as read-only as default for the entire class and as read-write with propagation for the
save
method.
-
What is Hibernate’s Spring JPA class for persistence?
-
What is the core Hibernate class for persistence?
-
Why is one preferred over the other?
Prev | TOC | Next |
---|---|---|