Announcement Announcement Module
Collapse
No announcement yet.
Spring Transaction Rollback Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring Transaction Rollback

    Trying to utilze Spring Transacrional capabilities to implement rollback upon database update failure. As it stands data from first "insert" statement updates database before throwing exception on second "insert" statement. Should either update both tables or rollback the entire process. What I'm I missing?
    Code:
    public class AllMember implements AllMemberDao {
        private DataSource dataSource;
        @Resource(name="dataSource")
        public void setDataSource(DataSource dataSource){
            this.dataSource = dataSource;
        }
    ...
    @Transactional(rollbackFor = Exception.class)
            public void readWriteRollbackTransaction(){
            log.info("-- AllMember.readWriteRollbackExampleTransaction -- expects transaction rollback");
    
            GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
                ctx.load("classpath*:app-context-annotation.xml");
                ctx.refresh();
    
        // execute your business logic here
            MemberDao memberDao = ctx.getBean("memberDao", MemberDao.class);
            UserRolesDao userRolesDao = ctx.getBean("userRoleDao", UserRolesDao.class);
            Member member = new Member();
            member.setFirstName("foo");
            member.setLastName("bar");
            member.setEmailAddress("foo.bar@gmail");
            member.setEnabled(true);
            member.setPassword("SHA1('hello123')");
    
            UserRoles role = new UserRoles();
    
            role.setAuthority("ROLE_USER");
           // int userId = memberDao.findByEmail(member.getEmailAddress()).getUserId();
            role.setUserId(13);
    
            memberDao.insert(member);
            userRolesDao.insertRole(role);
    
            throw new RuntimeException("readWriteRollbackExampleTransaction Exception");
    }
    
    }
    //xml

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSou rceTransactionManager">
    <property name="dataSource">
    <ref local="dataSource" />
    </property>
    </bean>


    <bean id="memberDSTransManager" class="com.core.dao.impl.AllMember" />
    <tx:annotation-driven transaction-manager="transactionManager"/>

  • #2
    Your code is wrong. NEVER create an applicationcontext, that should be created once and only once and that is at the start of your application. Use dependency injection to inject your daos into your class. Currently that breaks your tx management.

    Comment


    • #3
      Thanks for the tip. Problem solved.

      Comment

      Working...
      X