Transactional Spring is not rollback when some Excpetion is released

Asked

Viewed 182 times

0

I am using springboot 2.2.4 and mysql, as an example I have two classes: Client and Dependent:

import javax.persistence.*;
@Entity
public class Cliente {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
...
    @OneToOne(mappedBy = "cliente", cascade = CascadeType.PERSIST)
    private Depentende depentende;
}
import javax.persistence.*;
@Entity
public class Depentende {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
...
    @OneToOne
    private Cliente cliente;
}

import br.com.acdev.clientes.repository.ClienteRepository;
import br.com.acdev.clientes.repository.DependenteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ClienteService {
    @Autowired
    private ClienteRepository clienteRepository;
    @Autowired
    private DependenteRepository dependenteRepository;

@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Cliente criar(Cliente cliente) {
        cliente = clienteRepository.save(cliente);
        Depentende depentende = Depentende.builder().nome("joao").build();
        dependenteRepository.save(depentende);
        cliente.setDepentende(depentende);
        cliente = clienteRepository.save(cliente);
        throw new RuntimeException();
    }
}

in my application.yml

spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    password: root
    url: jdbc:mysql://localhost:3306/reservas?useTimezone=true&serverTimezone=UTC
    username: root
  jpa:
    database-platform: org.hibernate.dialect.MySQL5Dialect
    hibernate:
      ddl-auto: update
    properties:
      hibernate:
        format_sql: true
        show_sql: true

In my service I tried to force a situation to rollback everything with any Exception, I know I could omit the Propagation and the rollbackfor, but I left explicit to be sure. I have tested several variations on method calls, but whenever executed, entities are persisted in the bank, even with runtimeexcpetion or any other.

  • Have you made any settings to correctly use the Platformtransactionmanager?

  • I have not made any, other than @Repository, @ Service and @ Enablespringdatawebsupport in the main class

  • You are using jpa ?

  • @Brendonmiranda yes, using import javax.persistence. * and no . yml is jpa: database-Platform: org.hibernate.dialect.Mysql5dialect Hibernate: ddl-auto: update properties: Hibernate: format_sql: true show_sql: true

  • Posta seu Repository tbm

No answers

Browser other questions tagged

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