Pergunta

As part of a web app i am trying to build a registration process. after validating the process there are three sql statments to be performed. If any should fail then they should all be rolled back. However If i purposefully write the 3rd sql to fail (use a table name that doesnt exist). I see exception being thrown but the 1st and 2nd swl statments are not rolled back.

Can someone advise me on how this should be done.

from my application-context.xml

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

    <bean id="userDAO" class="com.doyleisgod.golf.database.JdbcUserDao">
      <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="registration" class="com.doyleisgod.golf.services.Registration"/>

    <tx:annotation-driven /> 

My registration service class

public class Registration implements IRegistration {
@Autowired JdbcUserDao userDAO;

@Override
@Transactional (rollbackFor = Exception.class)
public boolean registerUser(Object command) {
    return userDAO.registerUser(command);
}
}

my userDAO registration method

    public boolean registerUser(Object command)  {
    try {
        setUserCommand(command);
        sql = "INSERT INTO users (USERNAME,PASSWORD, ENABLED)VALUES ('"+username+"', '"+EncryptedPassword+"', TRUE);";
        getSimpleJdbcTemplate().update(sql);

        sql = "INSERT INTO user_roles (USERNAME,AUTHORITY)VALUES ('"+username+"', 'ROLE_USER');";
        getSimpleJdbcTemplate().update(sql);

        sql = "INSERT INTO users_details (USERNAME,FIRST_NAME, LAST_NAME, EMAIL_ADDRESS, HANDICAP)VALUES ('"+username+"', '"+firstname+"', '"+lastname+"', '"+email+"', '"+handicap+"');";
        getSimpleJdbcTemplate().update(sql);

    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
        return true;
}

Exampl of exception being thrown

    15-Feb-2012 21:13:48 org.springframework.jdbc.support.SQLErrorCodesFactory <init>
INFO: SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase]
org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [INSERT INTO users_details (USERNAME,FIRST_NAME, LAST_NAME, EMAIL_ADDRESS, HANDICAP)VALUES ('d', 'd', 'd', 'd', '0');]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'golf.users_details' doesn't exist

Can someone tell me what i have missed. Why when the 3rd sql statment fails do the other 2 transactions not get rolled back?

Foi útil?

Solução

Because you are catching the exception in your DAO, it is not thrown to the TransactionManager.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top