2011-05-29

JTA transactions with Hibernate, JBoss 6 and Spring 3

In this post I will show you how to use JTA transactions with JBoss 6 server, Spring 3 and Hibernate 3.

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>

61 comments:

  1. 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.

    Thanks
    Top 20 Core Java Interview question

    ReplyDelete
    Replies
    1. The development of artificial intelligence (AI) has propelled more programming architects, information scientists, and different experts to investigate the plausibility of a vocation in machine learning. Notwithstanding, a few newcomers will in general spotlight a lot on hypothesis and insufficient on commonsense application. machine learning projects for final year In case you will succeed, you have to begin building machine learning projects in the near future.

      Projects assist you with improving your applied ML skills rapidly while allowing you to investigate an intriguing point. Furthermore, you can include projects into your portfolio, making it simpler to get a vocation, discover cool profession openings, and Final Year Project Centers in Chennai even arrange a more significant compensation.

      Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

      The Nodejs Projects Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  2. Hi Michal,

    Great 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.

    ReplyDelete
  3. Hi Javin, thanks for visiting the blog. I did work with Spring AOP in a professional environment indeed. I may cover that in future.

    I 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).

    ReplyDelete
  4. Hi Marius, thanks for your insight. I retrieve it from JNDI where? What exactly do I delegate to JBoss in this scenario?

    ReplyDelete
  5. Interesting 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
  6. @amitstechblog

    In 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).

    ReplyDelete
  7. @Michal

    Here 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.

    ReplyDelete
  8. @Marius
    I 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?

    ReplyDelete
  9. Hey Michal,

    Sorry for the delay - unexpectedly busy weekend. I'll post something today (Monday).

    ReplyDelete
  10. As promised:

    http://second-kind-demon.blogspot.com/2011/06/spring-jpa-java-ee-jboss-deployment.html

    ReplyDelete
  11. hi 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..

    Cannot 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

    ReplyDelete
  12. Hi kuchai, it's possible not to use JTA.

    I 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.

    ReplyDelete
  13. hi michal..
    is 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?

    ReplyDelete
  14. bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">

    </bean

    ReplyDelete
  15. Hi,

    If you don't want JTA: http://blog.m1key.me/2011/05/non-jta-transactions-with-hibernate.html

    ReplyDelete
  16. but that one need to provide entitymanager for the transactionManager..i am using session factory..

    ReplyDelete
  17. i upgraded my spring jar in pom.xml to use 3.0.5 release..still i got the same error:(

    ReplyDelete
  18. can we communicate through google mail instead :)..add me at kushairi22@gmail.com

    ReplyDelete
  19. can i just change the sessionfactory bean id below to entitymanager ?

    bean 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

    ReplyDelete
  20. No, I don't think so. :) I think you need a proper setup of entity manager.

    ReplyDelete
  21. i 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..

    ReplyDelete
  22. the problem is only with the transactionManager...:(..

    ReplyDelete
  23. Does it mean you HAVE TO use session factory because something else demands it?

    ReplyDelete
  24. yup..i tried another way now..previously i install spring in jboss along with cxf jars using
    jbossws-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 ??

    ReplyDelete
  25. I did not encounter anything similar. Anyway, I'm sure it is possible to use session factory without JTA.

    If you're not using JTA, you need to give it the transaction manager yourself.


    How about this? @PersistenceUnit(unitName="custDb") SessionFactory factory;

    ReplyDelete
  26. 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...

    ReplyDelete
  27. Türkiye'nin en hızlı full oyun indirme sitesine davetlisiniz.
    https://torrentoyunum.com

    ReplyDelete
  28. 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.

    ReplyDelete
  29. 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
    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

    ReplyDelete
  30. 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

    ReplyDelete
  31. Thank you.. Get the Azerbaijan electronic visa through online e visa application to travel to Azerbaijan. Just follow 3 steps, fill application, upload document and make online payment for Azerbaijan e visa.

    ReplyDelete
  32. Hmm , 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.

    ReplyDelete
  33. You always comes with great stuff for your user. Thanks for being user friendly and Keep posting such great stuff 토토사이트

    ReplyDelete
  34. Thanks 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
  35. These type of articles keeps the users interest in the website. I found this one pretty fascinating and it should go into my collection. I am Impressed. Please keep going to write more content… 토토사이트

    ReplyDelete
  36. This article is an appealing wealth of useful informative that is interesting and well-written. I commend your hard work on this and thank you for this information. I know it very well that if anyone visits your blog, then he/she will surely revisit it again. Feel free to visit my website; 먹튀검증

    ReplyDelete
  37. Woah! I’m really digging the template/theme of this website. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between usability and visual appeal. Feel free to visit my website; 바카라사이트

    ReplyDelete
  38. Great info. Thank you for sharing this fascinating information together. I am so blessed to discover this. Feel free to visit my website; 바카라사이트

    ReplyDelete
  39. I 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.


    ReplyDelete
  40. Hii,
    This is great and awsome post for me. i loved to read your blog. it's really-really amazing. thanks for inspired me by your blog.Online Garen Store
    Buy Golden Jhumka
    Buy Online Seeds
    Buy Resin Pots
    Cocopeat Powder 2Kg
    Ludo Dice Ceramic Pot
    Set Of 6 Animal Planters

    ReplyDelete
  41. I was impressed by your writing. Your writing is impressive. I want to write like you.안전놀이터 I hope you can read my post and let me know what to modify. My writing is in I would like you to visit my blog.

    ReplyDelete
  42. The 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.

    ReplyDelete
  43. Thanks for the sharing this blog with us. I like it very much. 토토사이트

    ReplyDelete
  44. İnstagram takipçi satın al! İnstagram takipçi sitesi ile takipçi satın al sende sosyal medyada fenomen olmaya bir adım at. Sende hemen instagram takipçi satın almak istiyorsan tıkla:

    1- takipçi satın al

    2- takipçi satın al

    3- takipçi satın al

    ReplyDelete
  45. Incredible post I should state and much obliged for the data. Instruction is unquestionably a sticky subject. Be that as it may, is still among the main themes of our opportunity. I value your post and anticipate more. 메이저저사이트

    ReplyDelete
  46. I’m very pleased to discover this site. I want to to thank you for ones time for this particularly wonderful read!! I definitely savored every part of it and i also have you saved as a favorite to see new information on your blog. 먹튀사이트

    ReplyDelete
  47. Your site has excellent web content.I believe there was a great potential to change my mind once again after reading this article. I'm creating like you. If you are willing to travel to India, you will need a visa. Apply e visa to Indian online. Do you have any questions regarding e Visa India documents? You can find all frequently asked questions with the answers on eta Indian e visa website. You can also contact the visa support center by phone or by email. Apply for your visa easily and quickly.

    ReplyDelete

  48. Great article with great ideas! Thanks for such a valuable article.I really appreciate you for this great information. If you are interested to visit Pakistan then nowadays Pakistan business visa application process is everything online. The process is very simple if you have the right documents. First of all, check that you are a citizen of the eligible country and then apply for Pakistan visit visa. You can visit our Pakistan visa website and get all the information here.

    ReplyDelete
  49. Hello, 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.

    ReplyDelete
  50. Nice informative post on JTA transactions. Thanks for providing the code. Keep doing your good work. Thanks for sharing this wonderful post. Expecting more informative blogs from the author. Keep updating us technically and keep sharing it. Online Solicitation Of a Minor

    ReplyDelete
  51. I desire daily access to this kind of information. I'll read your content in full.
    Abogado De Trafico En Virginia

    ReplyDelete