A sample using Hibernate and Spring on Z2

This sample is very similar to Sample-hibernate-basic but differs in that we use the Spring framework throughout...

  • for assembly within the modules and to wire services between modules
  • for declarative transaction demarcation
  • for JPA entity manager injection

This is another practical application of How to Spring.

This sample is stored in z2-samples.spring-hibernate.

Check out How to transaction management for more infos on transaction management on Z2. See related examples


Z2 has the following Java Version requirements

Z2 Version Min. Java version required Max Java version supported Max language level
2.1 - 2.3.1 Java 6 Java 7 Java 7
2.4 - 2.5 Java 8 Java 8 Java 8
2.6 Java 9 Java 11 Java 10
2.7 Java 9 Java 11 Java 11
2.8 Java 9 Java 13 Java 13
2.9b Java 8 Java 8 Java 8
2.9.1 Java 11 Java 16 Java 15
2.9.1b Java 8 Java 8 Java 8
2.10 Java 11 Java 18 Java 18
master Java 11 ? Java 18

Note: Most samples suggest to use the master branch. You may choose another version branch (please check the respective repository).
Make sure you have a corresponding Java Development Kit (JDK) or Java Runtime Environment (JRE) installed. If in doubt, go to Download Java SE.

Note: Running v2.1-v2.3.1 on Java 8 is supported by specifying

(or 6, if that is your desired compilation language level) in <home>/run/bin/ By this the Java compiler version detection does not fall back to a lower level.

You need to run Java DB as network server on localhost. This is explained next.

The application will create a database "z2-samples"

Running a Java DB Network Server

Previously to Java 9, the Java SE Development Kit (JDK) by Oracle provided the Java DB - essentially the same as the Apache Derby DB. That is not the case anymore. However, we use that Database implementation in our samples. In order to run those samples that illustrate use of a relational database, please follow the instructions below to install and run Apache Derby. Could hardly be simpler.

Step 1: Download and Install

Unless you have done so already, download Apache Derby DB and follow the installation how-to.

Note: You do not need to unpack Apache Derby into some global folder on your system. Instead you may want to use some local folder under your user's home folder. There is no problem installing and runnning different instances and configurations at any time.

Step 2: Run

Let's assume you installed (well - unpacked) into a folder $DERBY_INSTALL. Also, let's assume some Java Runtime Environment is installed and ready.

Simply run the following on Linux or Mac OS:

java -jar lib/derbyrun.jar server start

On Windows run

java -jar lib\derbyrun.jar server start

That's it. Apache Derby will be waiting for connections on port 1527.

Run it

If you have the database, the fastest way to verify whether it runs is:

mkdir install
cd install

On Mac-OS or Linux run:


On Windows download the archive and unpack using the Windows explorer. Make sure to unpack into the installation folder previously created.

This will create a folder z2-base.core that contains the complete version 2.9 z2-base installation.

Check out the sample

git clone -b v2.10

On Mac OS or Linux run:

cd z2-base.core/bin

On Windows run:

cd z2-base.core\bin

(In order to check that z2 is up, when you see "Completed home process initialization", try http://localhost:8080/adm with user "z*" and password "z".)

When running, go to http://localhost:8080/spring-hibernate. You should see this:


Similar to Sample-hibernate-basic, the assumption of this example is that of a re-use domain module com.zfabrik.samples.spring-hibernate.domain that implements a "Thingy Repository" and is used from a web application that is in another module com.zfabrik.samples.spring-hibernate.web. The domain module exposes the Thingy Repository as a Z2 component - from a Spring application context defined bean - that is imported into the application context of the Web application and injected into the controller filter by Spring. The controller uses declarative transaction demarcation.

The domain module makes use of Hibernate's JPA implementation using Spring's entity manager injection and integrates with the transaction management provided by com.zfabrik.jta.

The domain module and its persistence context

The domain module com.zfabrik.samples.spring-hibernate.domain defines a persistence unit "thingies" in java/src.impl/META-INF/persistence.xml, i.e. in its implementation. That makes sense, as the XML file will be looked up with a class loader and we do not intent to retrieve from another module. Or, put differently, the persistence unit is not part of the module's API.

In order to integrate with the built-in transaction management the persistence.xml declares the JTA data source


and the Transaction Manager Lookup

<property name="hibernate.transaction.manager_lookup_class" value="com.zfabrik.hibernate.TransactionManagerLookup" />

The former points to the data source component com.zfabrik.samples.spring-hibernate.domain/DB, while the latter makes sure Hibernate can register with the transaction manager implementation.

The persistence unit defines only one entity. The Thingy as in That is an API-exposed type. We use the simplified pattern of exposing persistent objects in the API rather than using Data Transfer Objects (DTOs).

The application context of the module is defined in java/src.impl/META-INF/applicationContext.xml and looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" 
    xmlns:xsi="" xmlns:tx="" 

    <!-- annotation based config -->
    <context:component-scan base-package="com.zfabrik.samples.spring_hibernate" />
    <context:annotation-config />

    <!-- EntityManager injection -->
    <bean class="" />

    <!-- The actual EMF we use -->
    <bean id="entityManagerFactory"    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="thingies" />

In short:
  • We make sure we can use annotations
  • We enable entity manager injection
  • We initialize the entity manager factory from Spring

In the implementation class ThingyRepositoryImpl we make use of these capabilities and declare a Spring bean "thingyRepository":

public class ThingyRepositoryImpl implements ThingyRepository {
    private EntityManager em;

    public void store(Thingy thingy) {

    public Collection<Thingy> findAll() {
        return this.em.createQuery("select t from Thingy t").getResultList();

    public void delete(int id) {
        Thingy t = this.em.find(Thingy.class, id);
        if (t != null) {

In order to expose that bean as a Z2 component for re-use from other modules, we declare a component com.zfabrik.samples.spring-hibernate/repository:


# Expose Spring defined data source

# the context that defines the bean (more than one
# bean can be exposed like this)

# the bean name

that is based on the application context component com.zfabrik.samples.spring-hibernate/applicationContext:


# context config location is where the context is 
# actually defined. 

See also How to Spring for more details on these component types.

The web module, transaction boundaries, and service re-use

Let's turn to the Web application in com.zfabrik.samples.spring-hibernate.web/web. This one is also Spring configured. In contrast to the service module, its application context is not initialized from a Z2 component but rather from the Web app context (see web/WebContent/WEB-INF/web.xml). It is stored in web/WebContent/WEB-INF/applicationContext.xml and looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="" 
    xmlns:xsi="" xmlns:tx="" 
    xmlns:aop="" xmlns:security="" 

    <!-- Annotation Support -->
    <context:component-scan base-package="com.zfabrik.samples.spring_hibernate" />
    <context:spring-configured />
    <context:annotation-config />        

    This binds to java:comp/UserTransaction, which is ok in a Web app and considering
    that we configured Jetty JTA (see the transaction manager how-to in the Z2 Wiki and check environment/webServer/jetty.xml)


    <!-- outside of a web app we would bind to com.zfabrik.jta transaction manager like this

    <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="userTransaction">
            <bean class="com.zfabrik.tx.UserTransaction"/>

    <!-- make sure we can use @Transactional with the Spring aspect -->
    <tx:annotation-driven transaction-manager="transactionManager" mode="aspectj"/>

    <!-- import external services -->
    <bean id="thingyRepository" class="com.zfabrik.springframework.ComponentFactoryBean">
        <property name="componentName"  value="com.zfabrik.samples.spring-hibernate.domain/repository" />
        <property name="className"  value="com.zfabrik.samples.spring_hibernate.thingies.ThingyRepository" />


In short:

  • We enable annotation based configuration
  • We make the transaction manager available (for in-depth details see How to transaction management)
  • We enabled annotation based transaction demarcation (i.e. the use of @Transactional)
  • We import the Thingy Repository as a bean into this context.

The ControllerFilter is configured by Spring, although it is instantiated by the Jetty Web container. That is happening because we use the Spring aspect (see How to Spring once more) and it is annotated with @Configurable. We let Spring inject the Thingy Repository and we mark the doFilter method as transactional. Here is its skeleton:

public class ControllerFilter implements Filter {

  private ThingyRepository thingyRepository;

  public void doFilter(ServletRequest sreq, ServletResponse sres,    FilterChain chain) throws IOException, ServletException {

    // do some work here


  public void init(FilterConfig cfg) throws ServletException {}

  public void destroy() {}

A final word

A lot of what happens here requires the right libraries to be available in the sample modules. These are provided via the references in the files in the respective Java modules.
In other words: There is some non-trivial mechanics going on here that - in the long run - you should be aware of and try to read carefully through How to Spring. As a result you get a lot of coding and modularization convenience in the combination of Spring and Z2.

Updated by Henning Blohm 11 months ago · 20 revisions