I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application.
I want to use annotation based transactions (#Transactional), to not mess around with TransactionStatus commit, save, and rollback.
A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit.
Anyone ever see an issue?
In your config, would you have two transaction managers?
Would you have txManager1 and txManager2?
That's what I have with JPA, two different Spring beans that are transaction managers.
I guess you have 2 choices
If your use-cases never require updates to both databases within the same transaction, then you can use two JpaTransactionManagers, but I'm not sure you will be able to use the #Transactional approach? In this case, you would need to fallback on the older mechanism of using a simple TransactionProxyFactoryBean to define transaction boundaries, eg:
<bean id="firstRealService" class="com.acme.FirstServiceImpl"/>
<bean id="firstService"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="firstJpaTm"/>
<property name="target" ref="firstRealService"/>
<property name="transactionAttributes">
<props>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<!-- similar for your second service -->
If you are require a transaction spanning both databases, then you will need to use a JTA transaction manager. The API states:
This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.
What this means is that you will need to provide a JTA transaction manager. In our application, we use config similar to the following:
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName" value="appserver/jndi/path" />
</bean>
If you are deploying within an appserver, then the spring JtaTransactionManager needs to do a lookup to the real XA-compliant JTA transaction manager provided by the appserver. However, you can also use a standalone JTA transaction manager (but I haven't tried this myself yet)
As for configuring the Jpa persistence provider, I'm not that familiar. What JPA persistence provider are you using?
The code above is based on our approach, where we were using native Hibernate as opposed to Hibernate's JPA implementation. In this case, we were able to get rid of the two HibernateTransactionManager beans, and simply ensure that both SessionFactories were injected with the same JTA TM, and then use the tx:annotation-driven element.
Hope this helps
The only situation in which you can have two Spring transaction managers is if you never have both transactions open at one time. This is not intrinsically to do with distributed transactions - the same restrictions apply even if you want the two datasources to have completely separate (but potentially overlapping in time) transaction lifecyles.
Internally Spring's transaction managers all use Spring's TransactionSynchronizationManager which keeps a bunch of critical state in static ThreadLocal variables, so transaction managers are guaranteed to stomp all over each other's state.
Related
We are using JPA (Hibernate 4) with Spring 4 managing the JTA transactions. Since there are parts of the application using JDBC to access the database as well, we need to make sure JDBC and JPA join the same transaction to see what the other changed before commit.
You can find a test case for these questions on GitHub https://github.com/abenneke/sandbox/tree/master/spring-hibernate4-transaction
To have JDBC and JPA join the same transaction and see the changes the other made, we had to use the TransactionAwareDataSourceProxy for Hibernate/JPA as well. With all the other transaction configuration around, this however seems to be redundant. Did we miss something? Or is this the suggested way to achieve the requirement?
Thank you!
I think you can achieve the same outcome with much less configuration hassle if you stock to Hibernate and your JTA DataSource while you use the Session.doWork for your JDBC code.
You don't need TransactionAwareDataSourceProxy, since you want to use Transaction services anyway and not call DAO classes outside of a transactional service.
You need to add:
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
and make sure you supply it to testEntityManager
<bean id="testEntityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="testDataSource">
...
<property name="jpaDialect" ref="jpaDialect"/>
</bean>
Update
In one application we developed recently we too mixed JPA and JDBCTemplate and it worked nicely because Bitronix PoolingDataSource was instructed to always return the same connection for the current running thread.
For this you have to set the following Bitronix property:
shareTransactionConnections=true
I am using container managed transactions in my JavaEE application, but, as I have understood it, container managed entitymanagers lacks support for batch inserts. And now I have a case where I will insert a lot of data into the DB. Is it possible, in some way, to combine a container managed entitymanager with an application managed entitymanager in a bean?
If so, I could make a method in my bean that commits the data after I have called entitymanager.persist(myEntity); several times, making it a batch insert.
But to get that working, I now have to set #TransactionManagement(TransactionManagementType.BEAN) for the whole class/bean, making the whole bean application managed. But I want my other methods to be container managed, just one method (the method making batch inserts) to be application managed.
Is that possible or are there any other approaches for cases like this?
JDBC batching is a cross-cutting concern and you can get it working for all entity manager configurations.
First you need to set the following Hibernate properties:
<property name="hibernate.order_updates" value="true"/>
<property name="hibernate.order_inserts" value="true"/>
<property name="hibernate.jdbc.batch_versioned_data" value="true"/>
<property name="hibernate.jdbc.fetch_size" value="20"/>
<property name="hibernate.jdbc.batch_size" value="50"/>
Also make sure you use SEQUENCE or TABLE identifier generators since IDENTITY will disable JDBC batching
Question
How do I configure a JtaTransactionManager object with allowCustomIsolationLevels set to true via Spring such that the Spring configuration can be used across multiple application servers?
Background:
I have an application that is currently running out of JBossAS and I'm trying to get it to run in WebSphere. The only issue I'm currently having is getting the correct JTA Transaction Manager injected with the proper settings.
Here's the old setting
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName">
<value>java:/TransactionManager</value>
</property>
<property name="allowCustomIsolationLevels" value="true" />
</bean>
This worked since JBossAS has it's JTA Transaction Manager defined at JNDI location java:/TransactionManager. However, WebSphere does not have the same JNDI location.
Spring 2.5.x provides a way to get the JTA Transaction Manager in a generalized way.
<tx:jta-transaction-manager />
This gets the JtaTransactionManager object and defines it as a bean with the id transactionManager.
I looked in the Spring TX schema, but the only setting available is to set a specific isolation level, but not just to allow custom levels to be used (as defined elsewhere). How do I set the allowCustomIsolationLevels property using the tx:jta-transaction-manager tag?
Transaction Managers and Websphere:
Websphere does not use the typical jndi standard when supplying the transaction manager. Spring has worked around this by providing the org.springframework.transaction.jta.WebSphereUowTransactionManager that you can use to lookup the websphere transaction manager.
Datasource and Isolation Levels
You typically cannot change the isolation level of a datasource and I know you cannot change it when connecting from websphere to DB2 database (it's set as a parameter on the datasource configuration). The allowCustomIsolationLevels flag lets you select different data sources for different requested isolation levels..
See here and here
Using Spring:
can jta-transaction-manager use id as name so that I can pass it as REF to my service layer like below?
is tx:jta-transaction-manager can only be used for je22 container? I mean for Tomcat, I need to do it manually, like below:
<tx:jta-transaction-manager id="name_transactionmanager"/>
<bean id="projectService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager"
ref="name_transactionmanager"/>
<property name="target">
<bean
class="com.company.project.company.services.ServiceImpl"
init-method="init">
<property
name="HRappsdao"
ref="HRappsdao"/>
<property
name="projectdao"
ref="projectdao"/>
</bean>
</property>
<property name="transactionAttributes">
<props>
<prop key="store*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="bulkUpdate*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_SUPPORTS,readOnly</prop>
</props>
</property>
</bean>
For question 2
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="userTransaction">
<bean class="org.springframework.transaction.jta.JotmFactoryBean"/>
</property>
</bean>
Can tx:jta-transaction-manager use id as name so that I can pass it as REF to my service layer like below?
The <tx:jta-transaction-manager> exposes the transaction manager as a Bean in the Spring context with the name "transactionManager".
Can tx:jta-transaction-manager only be used with a J2EE container?
Quoting the Chapter 9. Transaction management from the Spring documentation:
Is an application server needed for transaction management?
The Spring Framework's transaction
management support significantly
changes traditional thinking as to
when a J2EE application requires an
application server.
In particular, you don't need an
application server just to have
declarative transactions via EJB. In
fact, even if you have an application
server with powerful JTA capabilities,
you may well decide that the Spring
Framework's declarative transactions
offer more power and a much more
productive programming model than EJB
CMT.
Typically you need an application
server's JTA capability only if you
need to enlist multiple transactional
resources, and for many applications
being able to handle transactions
across multiple resources isn't a
requirement. For example, many
high-end applications use a single,
highly scalable database (such as
Oracle 9i RAC). Standalone transaction
managers such as Atomikos Transactions
and JOTM are other options. (Of course
you may need other application server
capabilities such as JMS and JCA.)
The most important point is that with
the Spring Framework you can choose
when to scale your application up to a
full-blown application server. Gone
are the days when the only alternative
to using EJB CMT or JTA was to write
code using local transactions such as
those on JDBC connections, and face a
hefty rework if you ever needed that
code to run within global,
container-managed transactions. With
the Spring Framework, only
configuration needs to change so that
your code doesn't have to.
So, as explained in the third paragraph, if you want to work with multiple transactional resources, you'll need global transactions which involve a JTA capable application server. And JTA capable application server means a real J2EE container or a non J2EE container (like Tomcat) with a standalone transaction manager like Atomikos, JOTM, Bitronix, SimpleJTA, JBossTS or GeronimoTM/Jencks.
FWIW, I've seen lots of complains about JOTM, I think that GeronimoTM/Jencks lacks of documentation, I can't really say anything about JBossTSArjunaTS (except that it's a rock solid product), SimpleJTA and Bitronix have both good documentation and Atomikos is an impressive product greatly documented too. Personally, I'd choose Bitronix or Atomikos.
PS: Honestly, if this sounds like Chinese to you, you should maybe consider using a single database (if this is an option, go for it!) or consider using a real J2EE container like JBoss or GlassFish as I wrote in a previous answer. No offense but all this JTA stuff is not trivial and taking the JOTM path is not that simple if you don't really understand why you need it.
I am working on a project where we each service refers four separate data-source. Until now, we have been using ProxyFactoryBean to refer to the Dao target and the Transaction Intereceptor - something like this..
<bean id="readOnlyUserProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="readOnlyDao"/>
<property name="interceptorNames">
<list>
<value>readOnlyTransactionInterceptor</value>
</list>
</property>
</bean>
There are 3 other similar proxies for the different DAOs . All these refer to different transaction interceptors which in turn connect to different transaction managers. In short, each service connects to 4 dao proxies each of which refer a separate transaction interceptor, each of which in turn refer to a separate transaction manager connecting to 4 different data sources. All work fine till now with lazy="false".
Now, In order to optimize the performance, we wish to enable 'Lazy loading' and carry the hibernate session to the handler layer. We think that the best way for this would be through the 'TransactionProxyFactoryBean' as we do not want to use the OpenSessionInView approach .
We have tried some approaches but are stuck because we connect to 4 separate data sources through each service and in now way can we connect the four separate transaction managers to the 'TransactionProxyFactoryBean'. Therefore, we are not able to find a way to manage the transactions from different data sources in the handler/service layer.
I have just started on this work and do not have much experience in Spring transaction management. Kindly guide me on any possible approach I could take.
Managing transactions across multiple datasources is the job of the application server. The appserver will expose those transactions via the JTA API, and Spring can bridge from the JPA API to the Spring API using JtaTransactionManager.
As for how to configure the app server itself, that depends on what app server it is, you should do some research into that documention. It can be quite a complex operation, especially if the data sources are spread across different database servers (in which case you get into needing an XA Transaction Monitor, and it all gets very complicated).