Project

General

Profile

Sample-hibernate-basic » History » Version 24

Henning Blohm, 16.09.2018 21:43

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 19 Henning Blohm
This sample makes use of the [[Hibernate Add-on]] and is most likely the best documentation on how to use its supporting functionality. While some of the possibly complex seeming (but only needed once) glue code below is not required when using Spring (for example), as in [[Sample-spring-hibernate]], [[Sample-springds-hibernate]], this sample is most instructive on how Hibernate, Transaction Management, Z2, and the Jetty Web Container integrate with one another while closely sticking to standard descriptors (JPA) and naming (Java EE JNDI/Servlet).
8 14 Henning Blohm
9 5 Henning Blohm
h2. Prerequisites
10
11 22 Henning Blohm
{{include(Java Version Requirements)}}
12 21 Henning Blohm
13 11 Henning Blohm
You need to run Java DB as network server on localhost. This is explained next.
14 1 Henning Blohm
15 11 Henning Blohm
The application will create a database "z2-samples"
16 5 Henning Blohm
17 11 Henning Blohm
{{include(How to run Java db)}}
18
19
h2. Run the sample
20 5 Henning Blohm
21 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:
22 5 Henning Blohm
23
<pre><code class="ruby">
24
mkdir install
25 24 Henning Blohm
cd install
26
git clone -b v2.6 http://git.z2-environment.net/z2-base.core
27
git clone -b v2.6 http://git.z2-environment.net/z2-samples.hibernate-basic
28 5 Henning Blohm
29
# on Linux / Mac OS:
30
cd z2-base.core/run/bin
31
./gui.sh
32
33
# on Windows:
34
cd z2-base.core\run\bin
35
gui.bat
36
</code></pre>
37
38 10 Henning Blohm
When started, go to http://localhost:8080/hibernate-basic. You should see this:
39
40
!hibernate-basic.png!
41
42 5 Henning Blohm
h2. Details
43
44 7 Henning Blohm
A lot of the things happening here relate to what is explained in [[How to transaction management]].
45 1 Henning Blohm
46 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.
47
48
The domain module makes use of Hibernate's JPA implementation and integrates with the transaction management provided by *com.zfabrik.jta*.
49
50
Now, step-by-step.
51
52
h3. The domain module and its persistence context
53
54
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.
55
56
In order to integrate with the built-in transaction management the <code>persistence.xml</code> declares the JTA data source 
57
58
<pre><code class="xml">
59
<jta-data-source>components:com.zfabrik.samples.hibernate-basic.domain/DB</jta-data-source>
60
</code></pre>
61 1 Henning Blohm
62 14 Henning Blohm
and the _JTA Platform_ (Hibernate's transaction management abstraction since v4.3) 
63 1 Henning Blohm
64 7 Henning Blohm
<pre><code class="xml">
65 14 Henning Blohm
<property name="hibernate.transaction.jta.platform" value="com.zfabrik.hibernate.Z2JtaPlatform"/>
66 7 Henning Blohm
</code></pre>
67
68 14 Henning Blohm
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 that comes built-in with Z2 (other samples, such as [[Sample-jta-plain]], [[Sample-springds-hibernate]] show alternative approaches).
69 7 Henning Blohm
70
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).
71
72 12 Udo Offermann
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 to retrieve, store, and delete thingies.
73 7 Henning Blohm
74
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.
75
76
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*:
77
78
<pre><code class="java">
79 1 Henning Blohm
public class ThingyRepositoryImpl implements ThingyRepository {
80
	private EntityManagerFactory emf;
81
82 14 Henning Blohm
	/**
83
	 * Create the repo
84
	 */ 
85 1 Henning Blohm
	public ThingyRepositoryImpl() {
86 14 Henning Blohm
		/*
87
		 * We switch the context class loader so that Hibernate finds our persistence.xml.
88
		 * We use the EntityManagerUtil so that Hibernate doesn't freak out in a 
89
		 * no-Initial-Context-Factory (but URL for lookup) naming environment.
90
		 */
91 7 Henning Blohm
		this.emf = ThreadUtil.cleanContextExecute(
92 14 Henning Blohm
			this.getClass().getClassLoader(),
93 7 Henning Blohm
			new Callable<EntityManagerFactory>() {
94 14 Henning Blohm
				@Override
95 7 Henning Blohm
				public EntityManagerFactory call() throws Exception {
96 14 Henning Blohm
					return EntityManagerUtil.createEntityManagerFactory("thingies");
97
				}
98 7 Henning Blohm
			}
99
		);
100
	}
101
102
	@Override
103
	public void store(Thingy thingy) {
104
		this.em().persist(thingy);
105
	}
106
107
	@SuppressWarnings("unchecked")
108
	@Override
109
	public Collection<Thingy> findAll() {
110
		return this.em().createQuery("select t from Thingy t").getResultList();
111
	}
112
113
	@Override
114
	public void delete(int id) {
115
		Thingy t = this.em().find(Thingy.class, id);
116
		if (t != null) {
117
			this.em().remove(t);
118
		}
119
	}
120
121
	//
122
	// Uses the Entity Manager Util that holds on to EMs created from the passed on EMF
123
	// while the transaction is still open.
124
	//
125
	private EntityManager em() {
126
		return EntityManagerUtil.getEntityManager(
127 1 Henning Blohm
			IComponentsLookup.INSTANCE.lookup(
128 7 Henning Blohm
				"com.zfabrik.jta/userTransaction", 
129
				TransactionManager.class
130
			),
131
			this.emf
132
		);
133
	}
134
}
135 8 Henning Blohm
</code></pre>
136
137 1 Henning Blohm
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 (check out "a blog article on that":http://www.z2-environment.net/blog/2012/07/for-techies-protecting-java-in-a-modular-world-context-classloaders/).
138 16 Henning Blohm
139 18 Henning Blohm
We would normally use the JPA class "Persistence":http://docs.oracle.com/javaee/6/api/javax/persistence/Persistence.html to create an entity manager factory. Due to "HHH-8818":https://hibernate.atlassian.net/browse/HHH-8818 we do need to work around some JNDI issue by using the EntityManagerUtil (see its "source code":https://redmine.z2-environment.net/projects/z2-addons/repository/z2-addons-hibernate/revisions/master/entry/org.hibernate/java/src.api/com/zfabrik/hibernate/EntityManagerUtil.java here).
140 13 Udo Offermann
141 8 Henning Blohm
h3. The web module, transaction boundaries, and service re-use
142
143
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 is available under the JNDI name "java:comp/env/repos/thingies":
144
145
<pre><code class="xml">
146
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
147
  <New id="thingyRepository" class="org.eclipse.jetty.plus.jndi.Resource">
148
    <Arg>repos/thingies</Arg>
149
    <Arg>
150
      <New class="javax.naming.LinkRef">
151
        <Arg>components:com.zfabrik.samples.hibernate-basic.domain/repository?type=com.zfabrik.samples.hibernate_basic.thingies.ThingyRepository</Arg>
152
      </New>
153
    </Arg>
154
  </New>
155
</Configure>
156
</code></pre>
157
158
See also "Jetty JNDI":http://docs.codehaus.org/display/JETTY/JNDI.
159
160
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:
161
162
<pre><code class="java">
163
public class ControllerFilter implements Filter {
164
	
165
	// inject thingies repository (see WEB-INF/jetty-env.xml)
166
	@Resource(name="repos/thingies")
167
	private ThingyRepository thingyRepository;
168
	
169
...
170
}
171
</code></pre>
172
173
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
174
175
<pre><code class="java">
176
IComponentsLookup.INSTANCE.lookup("com.zfabrik.samples.hibernate-basic.domain/repository",ThingyRepository.class);
177
</code></pre>
178
179
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:
180
181
<pre><code class="java">
182
@Override
183
public void doFilter(final ServletRequest sreq, final ServletResponse sres,	final FilterChain chain) throws IOException, ServletException {
184
  HttpServletRequest req = (HttpServletRequest) sreq;
185
  if (req.getDispatcherType()==DispatcherType.REQUEST || req.getDispatcherType()==DispatcherType.ASYNC) {
186
    try {
187
      TransactionUtil.run(
188
        (UserTransaction) new InitialContext().lookup("java:comp/UserTransaction"),
189
        new Callable<Void>() {
190
          public Void call() throws Exception {
191
            chain.doFilter(sreq, sres);
192
            return null;
193
          }
194
        }
195
      );
196
    } catch (Exception e) {
197
      throw new ServletException(e);
198
    }
199
  } else {
200
    chain.doFilter(sreq, sres);
201 1 Henning Blohm
  }
202
}
203 15 Henning Blohm
</code></pre>
204
205
Finally note that we retrieved the transaction manager via the standard Java EE JNDI name @java:comp/UserTransaction@. Z2 uses Jetty as its Web container implementation. In order to have Jetty bind the transaction manager, we configure the Web server in "environment/webServer/jetty.xml":https://redmine.z2-environment.net/projects/z2-samples/repository/revisions/master/entry/environment/webServer/jetty.xml to retrieve the built-in transaction manager:
206
207
<pre><code class="xml">
208
...
209
210
	<New id="tx" class="org.eclipse.jetty.plus.jndi.Transaction">
211
		<Arg>
212
			<New class="com.zfabrik.tx.UserTransaction">
213
			</New>
214
		</Arg>
215
	</New>
216
...
217 1 Henning Blohm
</code></pre>
218 20 Henning Blohm
219
h2. How this sample makes use of MVNCR
220
221
This sample in conjunction with the [[Hibernate add-on]] is good example on how to use the Maven component repository (see [[How to Access a Maven Repository]]).
222
223
The situation is this:
224
225
* The add-on (the [[Hibernate add-on]] in this case) defines the artifacts required but may not define the actual artifact repository to use. After all it may be used with a locally hosted artifact repository.
226
* The solution environment (in this case this sample) may define the actual artifact repository but it should not need to repeat all the details on the actual artifact names and versions
227
228
To resolve this we use Maven component repository declarations and Maven component repository fragment declarations. 
229
230
* The repository declared as part of the sample in "environment/mavenDefault":https://redmine.z2-environment.net/projects/z2-samples/repository/revisions/master/entry/environment/mavenDefault has all the information on where to get artifacts from, while
231
* the fragment declared in the add-on at "org.hibernate/mvnFragment":https://redmine.z2-environment.net/projects/z2-addons/repository/z2-addons-hibernate/revisions/master/entry/org.hibernate/mvnFragment.properties declares the dependency roots it needs to have resolved from the (yet unknown - from the perspective of the add-on) MVNCR *environment/mavenDefault*.