In JEE, JTA allows transactions to be distributed across multiple resources. You don't need a JEE server though to run JTA transactions, Tomcat will do (possibly with a bit more hassle).
I decided to use JBoss 6 because it is a popular JEE server - but I would assume you can successfully run the code on any server as long as the data source is set correctly (plus with minor tweaks of server dependent stuff).
(I also wrote a post on non-jta transactions with Spring 3, JBoss 6 and Hibernate 3.)
applicationContext.xml
This is our Spring config file.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"> <property name="persistenceUnitName" value="Dogs" /> </bean> <bean id="dogsDao" class="me.m1key.springtx.dao.DogsDaoImpl" /> <bean id="dogsBean" class="me.m1key.springtx.beans.DogsBean" scope="singleton"> <property name="dogsDao" ref="dogsDao" /> </bean> <tx:annotation-driven transaction-manager="myTransactionManager" /> <tx:jta-transaction-manager /> <bean id="myTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" /> <bean class=" org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor " />Look closely, notice the jta-transaction-manager annotation and JtaTransactionManager.
persistence.xml
This is our persistence.xml. It's a bit different from the non-jta version.
… <persistence-unit name="Dogs" transaction-type="JTA"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <jta-data-source>java:/DogsDS</jta-data-source> <class>me.m1key.springtx.entities.Dog</class> <properties> <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.JBossTransactionManagerLookup" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="create" /> </properties> </persistence-unit> …Notice the transaction-type attribute. It's JTA as opposed to RESOURCE_LOCAL in the case of non-JTA. You must also specify transaction manager lookup class which is server dependent.
DAO
@PersistenceContext private EntityManager em; @SuppressWarnings("unchecked") @Transactional(readOnly = true) public List<Dog> retrieveAllDogs() { return em.createQuery("from Dog").getResultList(); }
That's it! To run this example you need a database server running. I'm using HSQLDB. You can download source code and there is a batch file there that runs this HSQLDB server. The application is to be deployed on JBoss 6.
You call the transactional operation by accessing http://localhost:8080/springtx-jta-0.0.1-SNAPSHOT/myurl.
pom.xml
For reference, the relevant parts of the POM file.
<dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.6.0.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-commons-annotations</artifactId> <version>3.2.0.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.0.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.0.Final</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>hsqldb</groupId> <artifactId>hsqldb</artifactId> <version>1.8.0.7</version> <type>jar</type> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.5.8</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <type>jar</type> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.0.3.RELEASE</version> <type>jar</type> <scope>compile</scope> </dependency> <dependency> <groupId>org.jboss.spec.javax.servlet</groupId> <artifactId>jboss-servlet-api_3.0_spec</artifactId> <version>1.0.0.Final</version> <scope>provided</scope> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency> </dependencies> <repositories> <repository> <id>r.j.o-groups-public</id> <url>https://repository.jboss.org/nexus/content/groups/public/</url> </repository> </repositories>
Great post man , you have indeed covered the topic in great details, I have worked with Spring some time back and looking for some practical advice on that specially on AOP front and defining point-cut and real usage of those , would be great if you could write your experience on those.
ReplyDeleteThanks
Top 20 Core Java Interview question
Hi Michal,
ReplyDeleteGreat post!
A quick comment: If you are setting up a JTA-based persistence.xml, you may as well let JBoss do the PU deployment and retrieve it from JNDI (since JBoss will deploy the persistence unit anyway). You can also suppress the default deployment by renaming the PU definition file or by using jboss-ignore.txt. This is just so that you don't end up with the persistence unit created twice.
Hi Javin, thanks for visiting the blog. I did work with Spring AOP in a professional environment indeed. I may cover that in future.
ReplyDeleteI already wrote some posts on plain AOP and I will probably focus on that now, if at all. It's a bit more powerful this way (plain AOP) than when used with Spring (but whether you need this extra power - manipulating class structure for instance - I'm not sure).
Hi Marius, thanks for your insight. I retrieve it from JNDI where? What exactly do I delegate to JBoss in this scenario?
ReplyDeleteInteresting read. I would trying out a similar setup with Glassfish as the JEE server and I assume the configuration would be similar. Do you have any idea about how are connections handled by spring in a distributed (JTA) transaction? I could see the spring class TransactionSynchronizationManager managing the connections as a thread local variable but not sure if this is the way spring guarantees same connection in a transaction
ReplyDelete@amitstechblog
ReplyDeleteIn a JTA scenario, Spring is deferring resource (e.g. connection) management to the transaction service itself. This is why it is required that resources themselves are JTA-aware (e.g. managed datasources, JMS connection factories, managed persistence units/contexts or as in this example, a persistence unit that is JTA-synchronized - through the usage of the transaction lookup manager).
@Michal
ReplyDeleteHere is a quick explanation of what I meant.
1) Any Java EE module (WAR, EJB-JAR, EAR) that contains a META-INF/persistence.xml will cause the application server to create (and deploy) a persistence unit
2) The persistence unit or a JTA-aware persistence context can be bound in JNDI - JBoss 5/6 support this in two separate ways:
a) through specific properties in persistence.xml
b) through the standard mechanism of resource reference registration - e.g. and in web.xml
3) Spring applications can just access the managed persistence unit and persistence context through JNDI lookups, like here:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa-setup-jndi
When I say 'delegate', I really mean that instead of instantiating a distinct EntityManagerFactory, a Spring application can simply reuse the one created by the application server).
Unfortunately, the comment space is not very friendly to code snippets :), so perhaps I'll try post a separate example of how this would look like.
Yeah, I'd love to see that!
ReplyDelete@Marius
ReplyDeleteI am bit confused by your statement - "In a JTA scenario, Spring is deferring resource (e.g. connection) management to the transaction service itself. " Do you mean if I use Bitronix as the distributed transaction manager, bitronix would do the connection management? If that's the case does it also mean TransactionSynchronizationManager is not involved when the transactions are distributed?
Hey Michal,
ReplyDeleteSorry for the delay - unexpectedly busy weekend. I'll post something today (Monday).
As promised:
ReplyDeletehttp://second-kind-demon.blogspot.com/2011/06/spring-jpa-java-ee-jboss-deployment.html
Thanks Marius!
ReplyDeletehi michal..i am not using jta..i use hibernate instead for jboss..is it possible ?? i stuck with this error..as far as i noticed, i dont have any redundancy in my pom.xml dependency..
ReplyDeleteCannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/dao.xml]: Invocation of init method failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field "logger" the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the referring class, org/springframework/transaction/support/AbstractPlatformTransactionManager, and the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) for the field's resolved type, org/springframework/transaction/support/AbstractPlatformTransactionManager, have different Class objects for that type
11:24:53,098 INFO [STDOUT] at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:102)
11:24:53,098 INFO [STDOUT] at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
11:24:53,098 INFO [STDOUT] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1350)
11:24:53,099 INFO [STDOUT] ... 94 more
Hi kuchai, it's possible not to use JTA.
ReplyDeleteI think the error is caused by the fact that you're supplying an *out-of-date* implementation of something, and NOT that you're not supplying it at all.
Thanks for visiting.
hi michal..
ReplyDeleteis it seems that the transactionManager cant be created..by default jboss 6 carter for JTA implementation..might be that causes the prob? as i was creating the transactionManager bean like below for hibernate?
bean id="transactionManager"
ReplyDeleteclass="org.springframework.orm.hibernate3.HibernateTransactionManager">
</bean
Hi,
ReplyDeleteIf you don't want JTA: http://blog.m1key.me/2011/05/non-jta-transactions-with-hibernate.html
but that one need to provide entitymanager for the transactionManager..i am using session factory..
ReplyDeletei upgraded my spring jar in pom.xml to use 3.0.5 release..still i got the same error:(
ReplyDeletecan we communicate through google mail instead :)..add me at kushairi22@gmail.com
ReplyDeleteUse entity manager then?
ReplyDeletecan i just change the sessionfactory bean id below to entitymanager ?
ReplyDeletebean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
hibernate.dialect=${hibernate.dialect}
hibernate.query.substitutions=false
hibernate.cache.use_second_level_cache=true
hibernate.transaction.factory_class=org.hibernate.transaction.CMTTransactionFactory
hibernate.transaction.manager_lookup_class=org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
hibernate.temp.use_jdbc_metadata_defaults false
hibernate.jdbc.batch_size=0
</property
No, I don't think so. :) I think you need a proper setup of entity manager.
ReplyDeletei using appfuse..by default there is some default jar using sessionfactory..i can override the files..but i not sure it may affect others or not..
ReplyDeletethe problem is only with the transactionManager...:(..
ReplyDeleteDoes it mean you HAVE TO use session factory because something else demands it?
ReplyDeleteyup..i tried another way now..previously i install spring in jboss along with cxf jars using
ReplyDeletejbossws-cxf-bin-dist..but now i only install the cxf jars without the spring jars..all the spring jars i provide in my pom.xml similiar like u except for the hibernate jar where we need to put the scope as provided...
BUT, jboss 6.0 Final is giving me class not found exception for the spring jar..seems that jboss 6 cant look into my war web-inf lib folder..do u previously encounter the same error ??
I did not encounter anything similar. Anyway, I'm sure it is possible to use session factory without JTA.
ReplyDeleteIf you're not using JTA, you need to give it the transaction manager yourself.
How about this? @PersistenceUnit(unitName="custDb") SessionFactory factory;
is there any where that we can just declare the transaction manager in the context.xml ?? how do you deploy ur app to jboss ?? i am using maven-war-plugin..and then excludes the web.xml...
ReplyDeleteTürkiye'nin en hızlı full oyun indirme sitesine davetlisiniz.
ReplyDeletehttps://torrentoyunum.com
aşk kitapları
ReplyDeleteyoutube abone satın al
cami avizesi
cami avizeleri
avize cami
no deposit bonus forex 2021
takipçi satın al
takipçi satın al
takipçi satın al
takipcialdim.com/tiktok-takipci-satin-al/
instagram beğeni satın al
instagram beğeni satın al
btcturk
tiktok izlenme satın al
sms onay
youtube izlenme satın al
no deposit bonus forex 2021
tiktok jeton hilesi
tiktok beğeni satın al
binance
takipçi satın al
uc satın al
sms onay
sms onay
tiktok takipçi satın al
tiktok beğeni satın al
twitter takipçi satın al
trend topic satın al
youtube abone satın al
instagram beğeni satın al
tiktok beğeni satın al
twitter takipçi satın al
trend topic satın al
youtube abone satın al
takipcialdim.com/instagram-begeni-satin-al/
perde modelleri
instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
instagram takipçi satın al
betboo
marsbahis
sultanbet
www.escortsmate.com
ReplyDeleteescortsmate.com
https://www.escortsmate.com
For latest information you have to visit web and on world wide-web I found this website as best web page for latest updates.Very nice post, I really love this website, keep it up thanks..To getting a visa for Turkey,There is a need to fill a visa on arrival Turkey through the Turkey visa online guide.
ReplyDeletetakipçi satın al
ReplyDeletetakipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
instagram takipçi satın al
takipçi satın al
instagram takipçi satın al
On your place I would make a video about these transactions and upload it on youtube. From here https://soclikes.com I would get more likes and views for it
ReplyDeleteHmm , very informative article! Thanks to author for it! Don't you think it's worth make a video on this article and post it on Twitter? You can also buy twitter followers in order to quickly wind up their number.
ReplyDeleteYou always comes with great stuff for your user. Thanks for being user friendly and Keep posting such great stuff 토토사이트
ReplyDeleteThanks for all the tips mentioned in this article! it’s always good to read things you have heard before and are implementing, but from a different perspective, always pick up some extra bits of information.
ReplyDelete경마사이트
경마
Great info. Thank you for sharing this fascinating information together. I am so blessed to discover this. Feel free to visit my website; 바카라사이트
ReplyDeleteI definitely enjoy every little bit of it. This is a great website and good stock.I want to thank you. Apply Online Indian visa, Fill and online Submit Visa Application Form Securely via India visa website.
ReplyDeleteThe website is good and the stock is good. Thanks for all you do. e medical visa India, you can get medical visa India online via Indian evisa portal.
ReplyDeleteThanks for the sharing this blog with us. I like it very much. 토토사이트
ReplyDeleteHello, I wanted to write a little information related to Visa. Are you interested in traveling to a country? Yes, you can evisa apply online. You can fill out your visa application form online through our Visacent website within 5 to 10 minutes. We offer visas to citizens of over 190 countries. You can read more information about visas through our website.
ReplyDeleteI desire daily access to this kind of information. I'll read your content in full.
ReplyDeleteAbogado De Trafico En Virginia
Excellent informative post. Keep posting more good blogs. Federal Criminal Defense Lawyer Maryland
ReplyDeleteObtaining a London visa for Indians is a significant step for Indian travelers eager to explore the iconic city of London and the United Kingdom at large. Whether you're drawn to the historic landmarks like the Tower of London and Buckingham Palace, the world-class museums, or the vibrant culture, understanding the visa requirements and application process is crucial. This guide will provide you with essential information about securing a London visa as an Indian citizen, including visa types, eligibility criteria, application procedures, and necessary documents. By being well-prepared, you can embark on your London adventure with confidence and make the most of your journey.
ReplyDeleteHello! I'd like to extend my heartfelt appreciation for the invaluable information shared on your blog. Experience convenience by apply Saudi visa online Save time, complete forms, and check requirements effortlessly via the official website for a stress-free travel experience.
ReplyDeleteI discovered a lot of useful information in your article. Visa Free Countries For New Zealand Citizens. New Zealand citizens are fortunate to possess a passport that opens doors to a wide range of visa-free countries around the world.
ReplyDeleteI really enjoyed your post. It's informative and well-written. Looking forward to more from you! For Canadian visa applicants in Riyadh, VFS Canada Riyadh provides efficient and convenient services to facilitate your visa application process. Book your appointment today.
ReplyDeleteNestled in the Eastern Himalayas, Sikkim is a stunning Indian state known for its breathtaking landscapes. The Gorgeous State of Sikkim in East Himalayas. With lush forests, dramatic mountains, and vibrant culture, it's a paradise for nature lovers and adventurers. Explore pristine lakes, monasteries, and trekking trails while immersing yourself in the rich local traditions. Sikkim is a hidden gem waiting to be discovered in the heart of the Himalayas.
ReplyDelete