How to rollback the database using Spring Framework

Asked

Viewed 914 times

0

I have this method that saves data in 3 different tables,

/**
 * 
 * @param user - de onde os dados do usuário serão retirados para gravar no banco
 * @throws GoogleAuthException - se houver algum erro ele retorna um erro a tela login
 * 
 * Este método cadastra um usuário com perfil geral, ele só será chamado se o usuário  não tiver nenhum perfil na tabela
 */
@Transactional
private Usuario cadastrarUsuario(GoogleUserInfo user) {

    Usuario usuario = new Usuario(user.getEmail(), user.getGiven_name(), user.getFamily_name(), StatusEnum.Ativo);
    Usuario usuarioSalvo = usuarioRepository.save(usuario);

    tracer.info(usuarioSalvo.toString());
    UsuarioPerfil usuarioPerfil = new UsuarioPerfil(RolesEnum.GERAL.getId(), usuarioSalvo.getIdUsuario(), Calendar.getInstance());
    usuarioPerfilRepository.save(usuarioPerfil);

    tracer.info(usuarioPerfil.toString());

    TelaUsuarioPerfilPrincipal telaPrincipalDoUsuario = 
            new TelaUsuarioPerfilPrincipal(usuarioSalvo.getIdUsuario(), RolesEnum.GERAL.getId(), ID_HOME_PAGE_PERFIL_GERAL);
    telaUsuarioPerfilPrincipalRepository.save(telaPrincipalDoUsuario);

    tracer.info(telaPrincipalDoUsuario.toString());

    return usuarioSalvo;
}

and would like to guarantee the atomicity of these transactions, I would like that in case the second or third save give error the birds that worked out were rollback in the database and were not saved, I tried to use the Annotation @Transactional Spring Boot but not successful.

These are my bank access variables

@Autowired
private UsuarioRepository usuarioRepository;

@Autowired
private UsuarioPerfilRepository usuarioPerfilRepository;

@Autowired
private TelaUsuarioPerfilPrincipalRepository telaUsuarioPerfilPrincipalRepository;

They are all interfaces inherited from JPARepository.

1 answer

2

By default, in the occurrence of a RuntimeException changes made to the transaction are rollback (except when treated in a block catch), already checked Exceptions will not perform rollback. As can be seen in the answer to this question Throwing a Runtimeexception causes the transaction to rollback, but Exception doesn’t in a spring boot app, which refers to doc Data Access spring.

If you want to do rollback regardless of which exception launched, it is possible to add in the annotation @Transactional which should carry out the rollback and which should not. Ex:

@Transactional(rollbackOn = Exception.class)
public void start() {
  ...
}
  • Hello I could only test your answer now, but I did not succeed in the rollback I made it to release an exception soon after saving the User, however he did not give rollback in the User table.

  • By chance, such using Mongodb?

  • No Mysql even.

  • In this case researching a little more about this problem in Spring Boot applications with Mysql database I found this question https://stackoverflow.com/a/49997835/8025145. Which caused the problem the Dialect version of Hibernate no longer supported by version 2 of Spring. It is worth checking if it is not your case.

  • So, young man? Problem solved?

  • passed me other activities here in the company and I still had no way to come back in this, the only test that I could do and that it worked was declaring explanatory a throw new RuntimeException() ai he gave rollback, but in case of normal exceptions did not work the rollback.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.