Project

General

Profile

How to Transaction Management » History » Version 15

Henning Blohm, 17.09.2012 15:22

1 10 Henning Blohm
h1. Transaction management in Z2
2 3 Henning Blohm
3 15 Henning Blohm
This page provides some hints and pointers on how to implement transaction management for modular applications on Z2. There are a few utilities provided with Z2 that may help you implement transaction handling for the simple cases, and the site provides examples that show how to address the more complicated cases.
4 1 Henning Blohm
5 12 Henning Blohm
Everything below is describing use and enabling of a Java Transaction API ("JTA":http://de.wikipedia.org/wiki/Java_Transaction_API) based approach to transaction management. 
6
7 15 Henning Blohm
Note that there is nothing in Z2 that prevents you from using a previously implemented Web application-local transaction management. The information on this page is most useful, if you have a modular application that requires transaction management also on a service level.
8 12 Henning Blohm
9
The following aspects will be discussed:
10
11
* The built-in, non-XA JTA implementation of Z2
12
* Controlling transactions in code
13
* Using Datasource components
14
* Using Hibernate JPA
15
* Using a full-blown transaction manager
16
* Integration with Jetty
17
* Integration with Spring
18
19
h2. The built-in, non-XA JTA implementation of Z2 (com.zfabrik.jta)
20
21
The "z2-base.base":http://redmine.z2-environment.net/projects/z2-base/repository/base repository contains the JTA 1.1 API and an implementation of it in the module *com.zfabrik.jta*. 
22
23
*Note*: This is not an XA-capable transaction manager. This implementation provides no atomic transaction control for more than one transactional resource!
24
25
But, this implementation is still most useful, if you do not need distributed transactions (which is preferable in most cases) and still want to benefit from the JTA API as an integration point.
26
27
Technically the implementation relies on Z2's _Unit of Work_ abstraction (see "Unit of Work and transaction management":http://www.z2-environment.eu/v21doc#Unit%20of%20Work%20and%20transaction%20management). As long as all interactions with an application are issued from a Web application this is completely transparent. When invoking code from other entry points, e.g. from an embedded scheduling service for example, this has an impact that will be discussed below.
28
29
The "TransactionManager":http://docs.oracle.com/javaee/6/api/javax/transaction/TransactionManager.html interface, as well as the "UserTransaction":http://docs.oracle.com/javaee/6/api/javax/transaction/UserTransaction.html interface are available from the component *com.zfabrik.jta/userTransaction* and can be looked up via the Z2 core API
30
31
<pre><code class="java">IComponentsLookup.INSTANCE.lookup("com.zfabrik.jta/userTransaction",TransactionManager.class)</code></pre>
32
33
or via JNDI as
34
35
<pre><code class="java">new InitialContext().lookup("components:com.zfabrik.jta/userTransaction?type=javax.transaction.TransactionManager")</code></pre>
36
37
and similarly for the UserTransaction interface.
38
39
This simple approach to JTA has been used in the samples [[Sample-hibernate-basic-TBD]] and [[Sample-spring-hibernate-TBD]].
40
41
h2. Controlling transactions in code
42
43
Now that you have a JTA implementation you need to indicate where transactions start and end. The most basic (and most understandable) approach to that is to use the UserTransaction interface. Typically in a flow like this:
44
45
<pre><code class="java">
46
UserTransaction ut = (UserTransaction) new InitialContext().lookup( JNDI_NAME );
47
ut.begin();
48
try {
49
  // do some work
50
} catch (Exception e) {
51
  logger.log(Level.WARNING,"Error at transaction boundary. Setting transaction to rollbackonly",e);
52
  ut.setRollbackOnly();
53
  throw e;
54
} finally {
55
  if (ut.getStatus()==Status.STATUS_ACTIVE) {
56
    ut.commit();
57
  } else {
58
    ut.rollback();
59
  }
60
}
61
</code></pre>
62
63
The constant *JNDI_NAME* is intentionally left undefined here. If you use *com.zfabrik.jta* you may use the name specified above. If the code above is part of a Servlet Filter that is supposed to begin and end transactions on the boundaries of a Web request, you can use the standard name "java:comp/UserTransaction" given you integrated the transaction management with Jetty (see below).
64
65
Now that we looked at it, fortunately you do not need to implement this yourself. Here are some alternatives:
66
67
* Use "TransactionUtil":http://redmine.z2-environment.net/projects/z2-base/repository/base/revisions/master/entry/com.zfabrik.jta/java/src.api/com/zfabrik/tx/TransactionUtil.java from *com.zfabrik.jta* that implements just the flow above.
68
* Use Spring's transaction management support including annotation based transaction demarcation, as for example in [[Sample-spring-hibernate-TBD]] and [[Sample-jta-spring]] (see also [[How to Spring]]).
69
* Use any of the many "Transaction Filter" implementations out there.
70
71
h2. Using DataSource components
72
73
A JDBC data source wraps JDBC connections, i.e. actual database connections, for re-use along the control flow. 
74
75
When accessing the same database multiple times within one transaction, you want to make sure you re-use the same (underlying) JDBC connection. That is, you may (typically) not have more than one (underlying) JDBC connection to the very same database that share the same (non-distributed) transaction. Hence the typical implementation associates a JDBC connection to a database with the transaction that is associated with the current thread of execution. Obviously there is a strong tie between the management of database connections and the transaction management system. JDBC data sources provide the accessor interface to database connections. You may hold of to a data source and ask it for a connection when needed, but you should not hold on to the actual connection object between invocations of your service interface. 
76
77
Z2 offers a built-in DataSource component type. This is useful, if you use *com.zfabrik.jta*. If you use another transaction management system, you should most likely use another data source implementation. See for example [[Sample-jta-plain]].
78
79
When using the built-in data source, you can look up the "DataSource":http://docs.oracle.com/javase/6/docs/api/javax/sql/DataSource.html interface via a component lookup, e.g. via JNDI like this:
80
81
<pre><code class="java">(DataSource) new InitialContext().lookup(COMPONENT_NAME?type=javax.sql.DataSource)</code></pre>
82
83 1 Henning Blohm
where *COMPONENT_NAME* has to be substituted by the real name of the data source component.
84
85
The built-in data sources have been used for example in [[Sample-hibernate-basic-TBD]] and [[Sample-spring-hibernate-TBD]].
86 12 Henning Blohm
87 15 Henning Blohm
An example definition can be found here: "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.
88
89
The component type *javax.sql.DataSource* is documented here: "DataSources":http://www.z2-environment.eu/v21doc#dataSources.
90 12 Henning Blohm
91
h2. Using Hibernate and JPA
92
93 13 Henning Blohm
Now you have a JTA implementation in place as well as data sources defined, assuming you want to use the "Java Persistence API":http://de.wikipedia.org/wiki/Java_Persistence_API you buy into yet another layer that needs to be integrated with the transaction management system. 
94
95
In JPA, the equivalent of a data base connection is the "EntityManager":http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html interface. And as with connections and data sources, you will want to reuse the entity manager instance across invocations within one transaction. An entity manager is created from an "EntityManagerFactory":http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManagerFactory.html given a definition of a _Persistence Unit_. We cannot go into all the details here. 
96
97
In Java EE environments, you may delegate the creation of entity managers to the container and have it _injected_ into your code using a corresponding annotation. The same comfort (and beyond that) can be achieved in Z2 even across modules using the Spring framework (see for example [[Sample-spring-hibernate-TBD]] and [[Sample-jta-spring]]). 
98
99
The underlying implementation however is always about associating an entity manager with the ongoing transaction. If you do not want to use Spring or want to fully understand the principle mechanics, you may use the "EntityManagerUtil":http://redmine.z2-environment.net/projects/z2-base/repository/base/revisions/master/entry/org.hibernate/java/src.api/com/zfabrik/hibernate/EntityManagerUtil.java of the module *org.hibernate* in *z2-base.base". This is how it is done in [[Sample-hibernate-basic]].
100
101
To connect a persistence unit (and hence the entity manager factory) with the transaction management and the data source to use, you add corresponding information to the file "META-INF/persistence.xml":http://redmine.z2-environment.net/projects/z2-samples/repository/revisions/master/entry/com.zfabrik.samples.hibernate-basic.domain/java/src.impl/META-INF/persistence.xml of your domain module. For example, the one in [[Sample-hibernate-basic]] looks like this:
102
103
<pre><code class="xml">
104
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
105
   <persistence-unit name="thingies" transaction-type="JTA">
106
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
107
      <jta-data-source>components:com.zfabrik.samples.hibernate-basic.domain/DB</jta-data-source>
108
      <class>com.zfabrik.samples.hibernate_basic.thingies.Thingy</class>
109
      <exclude-unlisted-classes>true</exclude-unlisted-classes>
110
      <properties>
111
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
112
         <property name="hibernate.hbm2ddl.auto" value="update" />
113
         <property name="hibernate.jdbc.batch_size" value="10" />
114
         <property name="hibernate.cache.use_second_level_cache" value="false" />
115
         <property name="hibernate.transaction.manager_lookup_class" value="com.zfabrik.hibernate.TransactionManagerLookup" />
116
       </properties>
117
  </persistence-unit>
118
</persistence>
119
</code></pre>
120
121
The noteworthy pieces are 
122
123
# The <jta-data-source/> definition that uses a DataSource JNDI name as discussed above.
124
# The <property name="hibernate.transaction.manager_lookup_class"/> declaration
125
126
The latter is required for Hibernate to find the transaction manager instance. Unfortunately Hibernate does not support a JNDI name for that. That's why the module *org.hibernate* provides an implementation you can use (it's really simple. See "TransactionManagerLookup":http://redmine.z2-environment.net/projects/z2-base/repository/base/revisions/master/entry/org.hibernate/java/src.api/com/zfabrik/hibernate/TransactionManagerLookup.java).
127
128
When not using *com.zfabrik.jta*, the value to specify differ of course. See also [[Samples-jta-plain]].
129
130 14 Henning Blohm
h2. Using a full-blown transaction manager
131 1 Henning Blohm
132 14 Henning Blohm
The sample [[Samples-jta-plain]] and [[Samples-jta-spring]] illustrate how to integrate the Atomikos transaction manager in a hand-wired application or in a Spring configured way resp. While it does help to understand the contents of this page, further details are to be found in the explanations of the samples.
133 1 Henning Blohm
134 14 Henning Blohm
h2. Integration with Jetty
135 1 Henning Blohm
136 14 Henning Blohm
The Jetty Web Container that comes with Z2 can be configured to integrate with a transaction manager (see e.g. "Jetty JNDI":http://docs.codehaus.org/display/JETTY/JNDI). The most notable impact is that you can use the JNDI name "java:comp/UserTransaction" to retrieve the UserTransaction interface from within the Web application. Note: This lookup is valid as long as the current thread's context class loader is the class loader of the Web application. Practically speaking this means it is safe to rely on this name while within the code of the Web application. When switching threads or invoking modules that may for some reason switch the context class loader or when invoked from another entry point to your application this may not be the case.
137 1 Henning Blohm
138 14 Henning Blohm
When using *com.zfabrik.jta*, having 
139 1 Henning Blohm
140 14 Henning Blohm
<pre><code class="xml">
141
  <New id="tx" class="org.eclipse.jetty.plus.jndi.Transaction">
142
    <Arg>
143
      <New class="com.zfabrik.tx.UserTransaction"/>
144
    </Arg>
145
  </New>
146
</code></pre>
147 1 Henning Blohm
148 14 Henning Blohm
in *environment/webServer/jetty.xml* does the trick. In other setups this varies. Please check the JTA samples mentioned above for an example of another configuration.
149 1 Henning Blohm
150 14 Henning Blohm
h2. Integration with Spring
151 1 Henning Blohm
152 14 Henning Blohm
Integration with Spring is yet another subject on its own. Please see the details on [[Samples-spring-hibernate-TBD]] for more on that.
153 6 Henning Blohm
154 14 Henning Blohm
h2. Summary
155 6 Henning Blohm
156 14 Henning Blohm
It is not as complex as it sounds. This page intentionally goes into some depths to give an understanding on a subject that often is ignored until failing, which is exactly when it is late to understand and correct assumptions. It will be best to pick one of the samples that best fits to your situation and take it from there.