-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 15 posts ] 
Author Message
 Post subject: JPA transcation rollBack is not working
PostPosted: Wed Dec 08, 2010 8:28 am 
Newbie

Joined: Tue Nov 02, 2010 10:55 am
Posts: 17
Hi all
I have done an application configuration using hybernate + JPA ,and atomikos for XA transcation management and spring 3.0 ,here every thing is working fine however insert operation, when exception is throwing the transcation should rollback,but it is not happening!!
here is a small flow for our application, in our manager level we are calling the businesss (here we are using Spring IOC)
my
Quote:
Manager.java
insertuser()
{
//here we are getting transcation support from spring.

business.insertuser();
}


business.java we are using one method insertuser()
Quote:
insertuser()
{
Tauser taUser=new Tauser();
taUser.setUsername("Maya");
taUser.setPassword("*****")
Dao.insertDetails(taUser);
throw new NullPointerException("checking transcation management"); // because of this exception throwing,it should rollback right,but its not happening.The property's are commiting in to the table.

}

and our dao.java class we are using one method insertuser(Object entity)

Quote:
void insertDetails(Object entity)
{
this.getJpaTemplate().persist(entity);
}


and our orm.xml
Quote:
<entity class="TaUser" name="TaUser">
<table name="ta_user" />
<attributes>
<id name="userId">
<column name="USER_ID" />
<generated-value strategy="AUTO" />
</id>
<basic name="userName">
<column name="USER_NAME" length="50" />
</basic>
</attributes>
</entity>

and my persistence.xml file is

Quote:
<persistence-unit name="shop" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:comp/env/jdbc/shobWeb</jta-data-source>
<mapping-file>META-INF/orm.xml</mapping-file>
<class>TaUser</class>
---------
---------
---------
<properties>
<property name="hibernate.transaction.manager_lookup_class"
value="com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"/>
</properties>
</persistence-unit>
</persistence>

and i configured my jndi in
Quote:
application/meta_inf/context.xml
<Resource name="jdbc/shobWeb" auth="Container"
driverClassName="com.mysql.jdbc.Driver"
user="root"
password="root"
type="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"
factory="com.mysql.jdbc.jdbc2.optional.MysqlDataSourceFactory"
url="jdbc:mysql://localhost:3306/shobWebSample"
explicitUrl="true"
pinGlobalTxToPhysicalConnection="true"
></Resource>


and my config file is
Quote:
config.xml

<beans:bean id="Manager"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<beans: property name="transactionManager">
<beans: ref bean="transactionManager" />
</beans: property>
<beans: property name="target">
<beans: ref local=" ManagerTarget" />
</beans: property>
<beans: property name="transactionAttributes">
<beans: props>
<beans: prop key="*">PROPAGATION_REQUIRED</beans:prop>
</beans: props>
</beans: property>
</beans: bean>

<beans: bean id="ManagerTarget"
class="Manager">
<beans: property name="Business" ref="Business" />
</beans: bean>
<beans: bean id="Business" class="PaymentsBusiness">
<beans: property name="Dao" ref=" Dao" />
</beans:bean>

<beans:bean id="Dao"
class=" Dao">
<beans: property name="jpaTemplate">
<beans: ref bean="jpaTemplate" />
</beans: property>
</beans:bean>

<beans:bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
<beans: property name="entityManagerFactory">
<beans: ref bean="entityManagerFactory" />
</beans: property>
</beans:bean>


<beans: bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<beans: property name="persistenceUnitName" value="shop" />
<beans: property name="jpaVendorAdapter">
<beans:bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<beans: property name="generateDdl" value="false" />
<beans: property name="showSql" value="true" />
</beans: bean>
</beans: property>
<beans: property name="persistenceXmlLocation">
<beans :value>classpath:META-INF/persistence.xml</beans: value>
</beans: property>
</beans: bean>

where is the issue? Actually when i am trying to update some property in table then transcation is working fine (rollback and commit is happening ),but when i am trying to do insert operation rollback is not happening.


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Thu Dec 09, 2010 8:50 am 
Beginner
Beginner

Joined: Fri Nov 26, 2010 8:25 am
Posts: 21
Hi there,

Could you post the full unedited code for your insert, and also for your update.

Many thanks
Kate.


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Fri Dec 10, 2010 3:54 am 
Newbie

Joined: Tue Nov 02, 2010 10:55 am
Posts: 17
based on your suggestion i updated my code

my
Code:
Manager.java      
      insertuser()
        {
        private static ApplicationContext springCtx;
       if (springCtx == null) {
         springCtx = (ApplicationContext) FacesContextUtils
               .getRequiredWebApplicationContext(FacesContext
                     .getCurrentInstance());
      }
       return springCtx.getBean("Manager");
        here  our transcation  will start
         business.insertuser();
        }
                 

Code:
business.java we are using one method insertuser() 
          insertuser()
          {
            Tauser taUser=new Tauser();
            taUser.setUsername("Maya");
            taUser.setPassword("*****")       
         Dao.insertDetails(taUser);
          throw new NullPointerException("checking transcation management"); // because  of this exception throwing,it should rollback right,but its not happening.The property's are commiting in to the table.
             
         }

and our dao.java class we are using one method insertuser(Object entity)
Code:
mport javax.persistence.EntityManager;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.ejb.HibernateEntityManager;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.util.Assert;
      public class dao extends JpaDaoSupport
     {
    void insertDetails(Object entity)
       {
            
        this.getJpaTemplate().persist(entity);       
       }
      }
       

and our
Code:
orm.xml 
         <entity class="TaUser" name="TaUser">
        <table name="ta_user" />
        <attributes>
            <id name="userId">
                <column name="USER_ID" />
                <generated-value strategy="AUTO" />
            </id>
            <basic name="userName">
                <column name="USER_NAME" length="50" />
            </basic>   
            </attributes>
    </entity>

and my pojo class is

TaUser.java (here we are not using annotations so we mapping with orm.xml file )
Code:
public class TaUser implements java.io.Serializable
   {
   private int userId;
   private String userName;
   
   public int getUserId() {
      return this.userId;
   }

   public void setUserId(int userId) {
      this.userId = userId;
   }
   public String getUserName() {
      return this.userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }
      
   }
   

and my persistence.xml file is
Code:
  <persistence-unit name="webhub" transaction-type="JTA">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:comp/env/jdbc/shobWeb</jta-data-source>
          <mapping-file>META-INF/orm.xml</mapping-file>
           <class>TaUser</class>
         ---------
         ---------
         ---------
         <properties>
            <property name="hibernate.transaction.manager_lookup_class"
            value="com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup"/>
         </properties>     
   </persistence-unit>
  </persistence>

and i configured my jndi in
Code:
application/meta_inf/context.xml
  <Resource name="jdbc/shobWeb" auth="Container" 
                      driverClassName="com.mysql.jdbc.Driver" 
                      user="root"
                      password="root" 
                      type="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"   
                      factory="com.mysql.jdbc.jdbc2.optional.MysqlDataSourceFactory"
                      url="jdbc:mysql://localhost:ebSample"
                      explicitUrl="true"
                      pinGlobalTxToPhysicalConnection="true"
                      ></Resource>


and my config file i am configuring trancaction management

Code:
my config.xml is
               
                <beans:bean id="Manager"
      class="Manager">
      <beans:property name="Business" ref="Business" />
   </beans:bean>
   <beans:bean id="Business" class="Business">
      <beans:property name="Dao" ref="Dao" />      
   </beans:bean>
            

<beans:bean id="Dao"
      class="Dao">
      <beans:property name="jpaTemplate">
         <beans:ref bean="jpaTemplate" />
      </beans:property>
   </beans:bean>

   <beans:bean id="jpaTemplate" class="org.springframework.orm.jpa.JpaTemplate">
      <beans:property name="entityManagerFactory">
         <beans:ref bean="entityManagerFactory"/>
      </beans:property>
   </beans:bean>

   <beans:bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <beans:property name="persistenceUnitName" value="webhub" />
      <beans:property name="jpaVendorAdapter">
         <beans:bean
            class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <beans:property name="generateDdl" value="false" />
            <beans:property name="showSql" value="true" />
            <beans:property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
         </beans:bean>
      </beans:property>
      <beans:property name="persistenceXmlLocation">
         <beans:value>classpath:META-INF/persistence.xml</beans:value>
      </beans:property>
      <beans:property name="persistenceUnitManager">
         <beans:ref bean="persistenceUnitManager"/>
      </beans:property>
   </beans:bean>

<beans:bean id="persistenceUnitManager"  class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
</beans:bean>      
here  i Configuread AOP Like this
    <aop:config>
            <aop:pointcut id="fooServiceOperation"  expression="execution(* com.live.webAppl.*.*.*(..))"/>         
          <aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
          </aop:config>
    <tx:advice id="txAdvice">
     <tx:attributes>
            <tx:method name="save*" rollback-for="UserExistsException"/>
            <tx:method name="remove*"/>
            <tx:method name="*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
   


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Fri Dec 10, 2010 4:12 am 
Beginner
Beginner

Joined: Fri Nov 26, 2010 8:25 am
Posts: 21
Hi,

You are throwing a NullPointerException after the insert has already happened. Once a transaction has been commited, you cannot rollback. In this case a rollback would only happen if a RuntimeException is thrown during the
Code:
this.getJpaTemplate().persist(entity);
Rollback occurs if a RuntimeException is thrown during a transaction, it is meant to undo any operations performed on the database to ensure that everything reverts back to the original state. Once a commit has happened that is effectively the end of the transaction.

Hope that helps,
Kate.


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Fri Dec 10, 2010 8:37 am 
Newbie

Joined: Tue Nov 02, 2010 10:55 am
Posts: 17
this.getJpaTemplate().persist(entity);
after this line data is committed into table (see it should not happen ?)
the data should be committed at the manager level ... but here it is happening at dao level .. so my spring transaction management not working properly right ?
plz reply me ?


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Fri Dec 10, 2010 8:58 am 
Beginner
Beginner

Joined: Fri Nov 14, 2008 7:34 pm
Posts: 24
enable and see database logs. maybe commit issued before exception


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Mon Dec 13, 2010 6:24 am 
Newbie

Joined: Tue Nov 02, 2010 10:55 am
Posts: 17
Quote:
commit issued before exception is happening .
plz could you tel how to solve this ?

log for when exception thrown
Quote:
DEBUG - AbstractPlatformTransactionManager.processRollback(850) | Participating transaction failed - marking existing transaction as rollback-only
DEBUG - JtaTransactionManager.doSetRollbackOnly(1060) | Setting JTA transaction rollback-only
580875 [http-8080-Processor20] INFO atomikos - setRollbackOnly() called for transaction PaymentsTransactions0000100672
DEBUG - AbstractPlatformTransactionManager.processRollback(843) | Initiating transaction rollback
580984 [http-8080-Processor20] INFO atomikos - afterCompletion ( STATUS_ROLLEDBACK ) called on Synchronization: org.hibernate.transaction.CacheSynchronization
580984 [http-8080-Processor20] INFO atomikos - afterCompletion ( STATUS_ROLLEDBACK ) called on Synchronization: org.hibernate.ejb.AbstractEntityManagerImpl$1@102d82c
580984 [http-8080-Processor20] INFO atomikos - rollback() done of transaction PaymentsTransactions0000100672

transaction roll backed ,but in database records are inserting .. any solution ?


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Mon Dec 13, 2010 7:08 am 
Beginner
Beginner

Joined: Fri Nov 14, 2008 7:34 pm
Posts: 24
but can you check mysql logs ?

also check jndi configuration, for atomikos it is a bit different
http://www.atomikos.com/Documentation/T ... egration33

<!-- Resource configuration for JDBC datasource-->
<Resource
name="jdbc/myDB"
auth="Container"
type="com.atomikos.jdbc.AtomikosDataSourceBean"
factory="com.atomikos.tomcat.BeanFactory"
uniqueResourceName="jdbc/myDB"
xaDataSourceClassName="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"
xaProperties.databaseName="test"
xaProperties.serverName="localhost"
xaProperties.port="3306"
xaProperties.user="USER"
xaProperties.password="PASSWORD"
xaProperties.url="jdbc:mysql://localhost:3306/test"
/>


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Mon Dec 13, 2010 7:54 am 
Newbie

Joined: Tue Nov 02, 2010 10:55 am
Posts: 17
hi maint175
really thanks for your quick reply, i think so what you mentioned above is ,we can use for Derby's JDBC driver ?. i tried to implement http://www.atomikos.com/Documentation/ConfiguringMySQL . i think it would be right ? .. reply me


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Mon Dec 13, 2010 8:32 am 
Beginner
Beginner

Joined: Fri Nov 14, 2008 7:34 pm
Posts: 24
I don't know what are pitfalls exist, but as for me - I'd better checked JTA without hibernate and spring at first, using plain jdbc.
After ensuring JTA is working at that level, next started with spring (transacted methods) and then hibernate.

Find where is the problem step by step.

Use some like below code to place in some servlet,

.....

Context ctx = new InitialContext();

// JDBC stuff
DataSource ds =
(DataSource)ctx.lookup("java:comp/env/jdbc/myDB");

UserTransaction ut = (UserTransaction)ctx.lookup("java:comp/UserTransaction");

Connection conn = ds.getConnection();

System.out.println("<<< beginning the transaction >>>");
ut.begin();

// JDBC statements
Statement stmt = conn.createStatement();
ResultSet rst =
stmt.executeQuery("select id, foo from testdata");
if(rst.next()) {
foo=rst.getInt(2);
}
System.out.println("foo = "+ foo +" (before completion)");

PreparedStatement pstmt = conn.prepareStatement("update testdata set foo=? where id=1");
pstmt.setInt(1,++foo);
pstmt.executeUpdate();

if (completion != null && completion.equals("commit")) {
System.out.println("<<< committing the transaction >>>");
ut.commit();
} else {
System.out.println("<<< rolling back the transaction >>>");
ut.rollback();
}

// we set foo to the value stored in the DB
stmt = conn.createStatement();
rst =
stmt.executeQuery("select id, foo from testdata");
if(rst.next()) {
foo=rst.getInt(2);
}
System.out.println("foo = "+ foo +" (after completion)");

conn.close();
System.out.println("<<< done >>>");

.....


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Thu Dec 23, 2010 11:34 am 
Newbie

Joined: Tue Nov 02, 2010 10:55 am
Posts: 17
hi
.MySQL has some limitations with XA transactions as you can see (http://dev.mysql.com/doc/refman/5.0/en/ ... tions.html), Because of using mysql 5.5,we could not get xa transaction(rollback not happening) properly,it does not support transaction .but in same configuration when i try with non xa transaction with atomickos ,transaction management is working fine .Is there is any other way to acheive xa transaction with atomikos using mysql.

My non XA data source from Atomikos.
Inside
Code:
meta-inf/context.xml

  <Transaction factory="com.atomikos.icatch.jta.UserTransactionFactory" />
          <Resource name="jjdbc/shobWeb" auth="Container"
          factory="org.apache.naming.factory.BeanFactory"
          type="com.atomikos.jdbc.nonxa.AtomikosNonXADataSourceBean"
          uniqueResourceName="myMySqlDatabase" driverClassName="com.mysql.jdbc.Driver"                url="jdbc:mysql://localhost:3306/testdb" user="root" password="root" maxPoolSize="20" reapTimeout="300" />

but we should use XA data source from Atomikos.
based on your post we tryied to configure my application/meta-inf/context.xml
is like this
Code:
<Resource   
              name="jdbc/shobWeb" auth="Container"
            type="com.atomikos.jdbc.AtomikosDataSourceBean"
             factory="org.apache.naming.factory.BeanFactory"
            uniqueResourceName="jdbc/testDb"
            xaDataSourceClassName="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource"
            xaProperties.serverName="192.168.1.108"
             xaProperties.user="root"
            xaProperties.password="root"
             url="jdbc:mysql://192.168.1.108:3306/testDb"/>

but when i try to run my application i am getting error like this
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/xaconfig/daoJPAConfig.xml]: Invocation of init method failed; nested exception is javax.naming.NamingException: No set method found for property: xaProperties.serverName. please help me..


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Thu Dec 23, 2010 5:52 pm 
Beginner
Beginner

Joined: Fri Nov 14, 2008 7:34 pm
Posts: 24
What is the daoJpaConfig.XML content ?


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Fri Dec 24, 2010 2:36 am 
Newbie

Joined: Tue Nov 02, 2010 10:55 am
Posts: 17
i got the solution..


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Fri Dec 24, 2010 4:26 am 
Beginner
Beginner

Joined: Fri Nov 26, 2010 8:25 am
Posts: 21
Hi there,

I'm glad you managed top solve the problem, could you please post your solution so that others with the same problem might benefit?

Regards,

Kate.


Top
 Profile  
 
 Post subject: Re: JPA transcation rollBack is not working
PostPosted: Sat May 31, 2014 12:55 pm 
Newbie

Joined: Tue May 27, 2014 11:13 pm
Posts: 1
Hello
I am coming into this task a bit green. Can you tell me if this JTA XADataSource implementation works with Apache Tomcat ?
Also what was the purpose of the <class> </class> tag entry in your persistence.xml file?
So far I have only dealt with javax.sql.DataSource type factories. I have never yet gotten javax.sql.XADataSource objects to work yet.
I am currently planning to try Atomikos so any pointers you can give me would be great. I see you use the
transactions-hibernate3-3.9.3.jar or its predecessor for your persistence. I do not know the purpose of that class you specify. Why is it specified in
your persistence.xml file?

Any other pointers?


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 15 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.