Announcement Announcement Module
Collapse
No announcement yet.
Transaction does not roll back , spring + hibernate + derby Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Transaction does not roll back , spring + hibernate + derby

    issue: Transaction does not roll back
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans">
    
    
        <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath:server.properties</value>
                    <value>classpath:log4j.properties</value>
                </list>
            </property>
        </bean>
    
        <!-- bean id="server-app" class="com.eas.lab.server.ServerApp"/>     -->
    
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
            <property name="driverClassName" value="${db.driver}"/>
            <property name="url" value="${db.url}"/>
            <property name="defaultAutoCommit" value="false" />
        </bean>
    
        <tx:annotation-driven transaction-manager="tx-manager"/>
    
        <!-- the transactional advice (i.e. what 'happens'; see the <aop:advisor/> bean below) -->
    
        <tx:advice id="txAdvice" transaction-manager="tx-manager">
            <!-- the transactional semantics... -->
            <tx:attributes>
                <!-- all methods starting with 'get' are read-only -->
                <tx:method name="get*" read-only="true"/>
                <!-- other methods use the default transaction settings (see below) -->
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
    
        <bean id="session-factory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="mappingLocations">
                <list>
                    <value>classpath:user.hbm.xml</value>
                    <value>classpath:product.hbm.xml</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <value>
                    hibernate.format_sql=true
                    hibernate.dialect=${db.dialect}
                    hibernate.show_sql="true"
                </value>
            </property>
        </bean>
    
        <bean id="user-dao"  class="com.eas.lab.server.dao.UserDaoImpl">
            <property name="sessionFactory" ref="session-factory"/>
        </bean>
    
        <bean id="product-dao"  class="com.eas.lab.server.dao.ProductDaoImpl">
            <property name="sessionFactory" ref="session-factory"/>
        </bean>
    
        <bean id="user-service"  class="com.eas.lab.server.UserServiceImpl">
            <property name="userDao" ref="user-dao"/>
            <property name="productDao" ref="product-dao"/>
        </bean>
    
    
        <bean id="tx-manager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="session-factory"/>
        </bean>
    
    </beans>
    now the code

    Code:
    package com.eas.lab.server;
    
    import com.eas.lab.data.Product;
    import com.eas.lab.data.User;
    import com.eas.lab.server.dao.ProductDao;
    import com.eas.lab.server.dao.UserDao;
    import org.apache.log4j.Logger;
    import org.hibernate.SessionFactory;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.Collection;
    
    
    @Transactional
    public class UserServiceImpl implements UserService {
    
        private static final Logger logger = Logger.getLogger(ServerApp.class.getName());
    
        private SessionFactory sessionFactory;
    
        private UserDao userDao;
        private ProductDao productDao;
    
        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }
    
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    
        public void setProductDao(ProductDao productDao) {
            this.productDao = productDao;
        }
    
        @Override
        public void printUsers() {
            try {
                Collection<User> users = userDao.findUsers();
                for (User user : users) {
                    logger.info(user);
                }
            } catch (Exception e) {
                logger.info("Error occurred..." + e);
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void printProducts() {
            try {
                Collection<Product> products = productDao.getAll();
                for (Product product : products) {
                    logger.info(product);
                    // throw new Exception("rollback");
                }
            } catch (Exception e) {
                logger.info("Error occurred..." + e);
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void update() throws Exception {
            Collection<User> users = userDao.findUsers();
            for (User user : users) {
                user.setName(user.getId() + "-" + user.getName());
                userDao.save(user);
            }
            Collection<Product> products = productDao.getAll();
            for (Product product : products) {
                product.setName(product.getName() + "-" + product.getId());
                productDao.save(product);
                 throw new Exception("rollback");
            }
        }
    }

  • #2
    logs

    Code:
    Connected to the target VM, address: '127.0.0.1:58463', transport: 'socket'
    Apr 17, 2011 11:26:02 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1055e55f: startup date [Sun Apr 17 23:26:02 EDT 2011]; root of context hierarchy
    Apr 17, 2011 11:26:03 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [server-spring-config.xml]
    Apr 17, 2011 11:26:03 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
    INFO: Loading properties file from class path resource [server.properties]
    Apr 17, 2011 11:26:03 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
    INFO: Loading properties file from class path resource [log4j.properties]
    Apr 17, 2011 11:26:03 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d6d835f: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,txAdvice,userServiceOperation,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,session-factory,user-dao,product-dao,user-service,tx-manager]; root of factory hierarchy
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    Apr 17, 2011 11:26:04 PM org.springframework.orm.hibernate3.LocalSessionFactoryBean buildSessionFactory
    INFO: Building new Hibernate SessionFactory
    Apr 17, 2011 11:26:06 PM org.springframework.orm.hibernate3.HibernateTransactionManager afterPropertiesSet
    INFO: Using DataSource [org.apache.commons.dbcp.BasicDataSource@6bd8c046] of Hibernate SessionFactory for HibernateTransactionManager
    [2011-04-17 23:26:07,518] INFO  [main] UserServiceImpl.java:60 - Product{id=1, name='Product#1-1-1-1-1', type='eq', lastUpdatedBy='1', lastUpdated=0}
    [2011-04-17 23:26:07,533] INFO  [main] UserServiceImpl.java:60 - Product{id=2, name='Product#2-2', type='swap', lastUpdatedBy='1', lastUpdated=0}
    [2011-04-17 23:26:07,533] INFO  [main] UserServiceImpl.java:60 - Product{id=3, name='Product#3-3', type='irp', lastUpdatedBy='1', lastUpdated=0}
    [2011-04-17 23:26:07,564] INFO  [main] UserServiceImpl.java:47 - User{id=1, name='1-1-1-1-Jack'}
    [2011-04-17 23:26:07,596] INFO  [main] UserServiceImpl.java:47 - User{id=2, name='2-2-2-2-Jill'}
    [2011-04-17 23:26:07,596] INFO  [main] UserServiceImpl.java:47 - User{id=3, name='3-3-3-3-stone'}
    java.lang.Exception: rollback
    	at com.eas.lab.server.UserServiceImpl.update(UserServiceImpl.java:80)
    	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    	at java.lang.reflect.Method.invoke(Method.java:597)
    	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    	at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
    	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    	at $Proxy6.update(Unknown Source)
    	at com.eas.lab.server.ServerApp.main(ServerApp.java:36)
    [2011-04-17 23:26:07,878] INFO  [main] UserServiceImpl.java:60 - Product{id=1, name='Product#1-1-1-1-1-1', type='eq', lastUpdatedBy='1', lastUpdated=0} <--shold not update
    [2011-04-17 23:26:07,878] INFO  [main] UserServiceImpl.java:60 - Product{id=2, name='Product#2-2', type='swap', lastUpdatedBy='1', lastUpdated=0}
    [2011-04-17 23:26:07,878] INFO  [main] UserServiceImpl.java:60 - Product{id=3, name='Product#3-3', type='irp', lastUpdatedBy='1', lastUpdated=0}
    [2011-04-17 23:26:07,878] INFO  [main] UserServiceImpl.java:47 - User{id=1, name='1-1-1-1-1-Jack'}
    [2011-04-17 23:26:07,943] INFO  [main] UserServiceImpl.java:47 - User{id=2, name='2-2-2-2-2-Jill'}
    [2011-04-17 23:26:07,943] INFO  [main] UserServiceImpl.java:47 - User{id=3, name='3-3-3-3-3-stone'}

    Comment


    • #3
      Hi,

      Please note from Spring's documentation's section 9.5.3
      However, please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException. (Errors will also - by default - result in a rollback.) Checked exceptions that are thrown from a transactional method will not result in the transaction being rolled back.
      So i think you need to create a custom exception which extends from RuntimeException and throw it for rollback. Also remember to configure it in your application context.

      Hope this helps!!!!

      Comment

      Working...
      X