Project

General

Profile

Sample-hibernate-basic » History » Version 9

Henning Blohm, 17.09.2012 17:22

1 1 Henning Blohm
h1. A plain Hibernate on Z2 sample
2 2 Henning Blohm
3 3 Henning Blohm
Note that Hibernate is used in other samples as well, such as [[Sample-jta-plain]], [[Sample-jta-spring]], and others. This sample shows the minimal things to do to use Hibernate as an implementation of the Java Persistence API ("JPA":http://de.wikipedia.org/wiki/Java_Persistence_API). 
4 4 Henning Blohm
5 5 Henning Blohm
This sample is stored in the repository "z2-samples.hibernate.basic":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic. 
6
7
h2. Prerequisites
8
9
You need the *z_tx_tests* database on a local MySQL database system. Start the MySQL client as the root user and run:
10
11
<pre><code class="SQL">
12
create database z_tx_tests;
13
grant all on z_tx_tests.* to tx@localhost identified by 'tx';
14
</code></pre>
15
16
h2. Run it
17
18 6 Henning Blohm
Like all samples, also this sample can be run as in [[How to run a sample]]. If you have the database, the fastest way to verify whether it runs is:
19 5 Henning Blohm
20
<pre><code class="ruby">
21
mkdir install
22
cd install 
23
git clone -b master http://git.z2-environment.net/z2-base.core
24
git clone -b master http://git.z2-environment.net/z2-samples.hibernate-basic
25
26
# on Linux / Mac OS:
27
cd z2-base.core/run/bin
28
./gui.sh
29
30
# on Windows:
31
cd z2-base.core\run\bin
32
gui.bat
33
</code></pre>
34
35
h2. Details
36
37 7 Henning Blohm
A lot of the things happening here relate to what is explained in [[How to transaction management]].
38 1 Henning Blohm
39 7 Henning Blohm
The assumption of this example is that of a re-use domain module *com.zfabrik.samples.hibernate-basic.domain* that implements a "Thingy Repository" and is used from a web application that is in another module *com.zfabrik.samples.hibernate-basic.web*. The domain module exposes the Thingy Repository as a Z2 component that is bound by the Web app as an environment (ENC) variable and injected into the controller filter by the Web container.
40
41
The domain module makes use of Hibernate's JPA implementation and integrates with the transaction management provided by *com.zfabrik.jta*.
42
43
Now, step-by-step.
44
45
h3. The domain module and its persistence context
46
47
The domain module *com.zfabrik.samples.hibernate-basic.domain* defines a persistence unit "thingies" in "java/src.impl/META-INF/persistence.xml":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic/revisions/master/entry/com.zfabrik.samples.hibernate-basic.domain/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.
48
49
In order to integrate with the built-in transaction management the <code>persistence.xml</code> declares the JTA data source 
50
51
<pre><code class="xml">
52
<jta-data-source>components:com.zfabrik.samples.hibernate-basic.domain/DB</jta-data-source>
53
</code></pre>
54
55
and the _Transaction Manager Lookup_ 
56
57
<pre><code class="xml">
58
<property name="hibernate.transaction.manager_lookup_class" value="com.zfabrik.hibernate.TransactionManagerLookup" />
59
</code></pre>
60
61
The former points to the data source component "com.zfabrik.samples.hibernate-basic.domain/DB":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic/revisions/master/entry/com.zfabrik.samples.hibernate-basic.domain/DB.properties, while the latter makes sure Hibernate can register with the transaction manager implementation. 
62
63
The persistence unit defines only one entity. The Thingy as in "Thingy.java":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic/revisions/master/entry/com.zfabrik.samples.hibernate-basic.domain/java/src.api/com/zfabrik/samples/hibernate_basic/thingies/Thingy.java. 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).
64
65
Also, the domain module exposes the interface of the "Thingy Repository":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic/revisions/master/entry/com.zfabrik.samples.hibernate-basic.domain/java/src.api/com/zfabrik/samples/hibernate_basic/thingies/ThingyRepository.java. This interface is used by the Web application retrieve, store, and delete thingies.
66
67
The implementation of the Thingy Repository, "ThingyRepositoryImpl":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic/revisions/master/entry/com.zfabrik.samples.hibernate-basic.domain/java/src.impl/com/zfabrik/samples/hibernate_basic/impl/thingies/ThingyRepositoryImpl.java is not a public type. Instead, it is instantiated and held on to via a Z2 component lookup from the Web app on the component "com.zfabrik.samples.hibernate-basic.domain/repository":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic/revisions/master/entry/com.zfabrik.samples.hibernate-basic.domain/repository.properties.
68
69
In ThingyRepositoryImpl, in order to access and re-use the JPA Entity Manager for the persistence unit "thingies" we use EntityManagerUtil from *org.hibernate* with a Entity Manager Factory that we create upon service instantiation and using the user transaction implementation of *com.zfabrik.jta*:
70
71
<pre><code class="java">
72
public class ThingyRepositoryImpl implements ThingyRepository {
73
	private EntityManagerFactory emf;
74
75
	public ThingyRepositoryImpl() {
76
		// 
77
		// initially create the EMF for this domain
78
		//		
79
		this.emf = ThreadUtil.cleanContextExecute(
80
			this.getClass().getClassLoader(), 
81
			new Callable<EntityManagerFactory>() {
82
				public EntityManagerFactory call() throws Exception {
83
					return Persistence.createEntityManagerFactory("thingies");
84
				};
85
			}
86
		);
87
	}
88
89
	@Override
90
	public void store(Thingy thingy) {
91
		this.em().persist(thingy);
92
	}
93
94
	@SuppressWarnings("unchecked")
95
	@Override
96
	public Collection<Thingy> findAll() {
97
		return this.em().createQuery("select t from Thingy t").getResultList();
98
	}
99
100
	@Override
101
	public void delete(int id) {
102
		Thingy t = this.em().find(Thingy.class, id);
103
		if (t != null) {
104
			this.em().remove(t);
105
		}
106
	}
107
108
	//
109
	// Uses the Entity Manager Util that holds on to EMs created from the passed on EMF
110
	// while the transaction is still open.
111
	//
112
	private EntityManager em() {
113
		return EntityManagerUtil.getEntityManager(
114
			IComponentsLookup.INSTANCE.lookup(
115
				"com.zfabrik.jta/userTransaction", 
116
				TransactionManager.class
117
			),
118
			this.emf
119
		);
120
	}
121
}
122
</code></pre>
123
124
Note that when creating the entity manager factory, we have to make sure the right context class loader is set so that the persistence unit definition will be picked up by Hibernate. This is a general pattern when initializing services in a modular application: You need to distinguish when the service's context matters vs. when the caller's context matters.
125 8 Henning Blohm
126
h3. The web module, transaction boundaries, and service re-use
127
128 9 Henning Blohm
Let's turn to the Web application in *com.zfabrik.samples.hibernate-basic.web/web*. And let's start with how the Thingy Repository is accessed from the Web app. In this example we do not use Spring or direct lookups, instead we use the Web container provided dependency injection mechanisms. In "WebContent/WEB-INF/jetty-env.xml":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic/revisions/master/entry/com.zfabrik.samples.hibernate-basic.web/web/WebContent/WEB-INF/jetty-env.xml we bind the result of a JNDI lookup for the repository implementation component to the _Environment Naming Context_ (ENC) variable "repos/thingies". This is java EE mechanics. It means that from within the Web app, the repository would available under the JNDI name "java:comp/env/repos/thingies":
129 8 Henning Blohm
130
<pre><code class="xml">
131
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
132
  <New id="thingyRepository" class="org.eclipse.jetty.plus.jndi.Resource">
133
    <Arg>repos/thingies</Arg>
134
    <Arg>
135
      <New class="javax.naming.LinkRef">
136
        <Arg>components:com.zfabrik.samples.hibernate-basic.domain/repository?type=com.zfabrik.samples.hibernate_basic.thingies.ThingyRepository</Arg>
137
      </New>
138
    </Arg>
139
  </New>
140
</Configure>
141
</code></pre>
142
143
See also "Jetty JNDI":http://docs.codehaus.org/display/JETTY/JNDI.
144
145
Anyway. Now, in the "ControllerFilter":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic/revisions/master/entry/com.zfabrik.samples.hibernate-basic.web/java/src.impl/com/zfabrik/samples/hibernate_basic/impl/web/ControllerFilter.java we inject the Thingy Repository like this:
146
147
<pre><code class="java">
148
public class ControllerFilter implements Filter {
149
	
150
	// inject thingies repository (see WEB-INF/jetty-env.xml)
151
	@Resource(name="repos/thingies")
152
	private ThingyRepository thingyRepository;
153
	
154
...
155
}
156
</code></pre>
157
158
Alternatively, if you think this is a little overkill, you might as well use a direct lookup, either with JNDI using the name in the XML or via Z2's component lookup
159
160
<pre><code class="java">
161
IComponentsLookup.INSTANCE.lookup("com.zfabrik.samples.hibernate-basic.domain/repository",ThingyRepository.class);
162
</code></pre>
163
164
Finally a word on transaction management. Transaction boundaries are controlled by the "TransactionFilter":http://redmine.z2-environment.net/projects/z2-samples/repository/z2-samples-hibernate-basic/revisions/master/entry/com.zfabrik.samples.hibernate-basic.web/java/src.impl/com/zfabrik/samples/hibernate_basic/impl/web/TransactionFilter.java contained in the sample. We make use of *TransactionUtil* from *com.zabrik.jta* to wrap the actual web app request in a transaction:
165
166
<pre><code class="java">
167
@Override
168
public void doFilter(final ServletRequest sreq, final ServletResponse sres,	final FilterChain chain) throws IOException, ServletException {
169
  HttpServletRequest req = (HttpServletRequest) sreq;
170
  if (req.getDispatcherType()==DispatcherType.REQUEST || req.getDispatcherType()==DispatcherType.ASYNC) {
171
    try {
172
      TransactionUtil.run(
173
        (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"),
174
        new Callable<Void>() {
175
          public Void call() throws Exception {
176
            chain.doFilter(sreq, sres);
177
            return null;
178
          }
179
        }
180
      );
181
    } catch (Exception e) {
182
      throw new ServletException(e);
183
    }
184
  } else {
185
    chain.doFilter(sreq, sres);
186
  }
187
}
188
</code></pre>