Project

General

Profile

Sample-hibernate-basic » History » Version 7

Henning Blohm, 17.09.2012 16:57

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.