@Transactional服务方法回滚休眠更改

时间:2019-05-18 18:49:03

标签: java spring hibernate spring-boot

我在@Service类中有一个方法,该方法在两个不同的@Service类中调用两个不同的方法。这两种不同的方法(通过休眠)将两个实体保存在数据库中,并且它们都可能引发某些异常。 我想,如果引发异常,则独立于哪个@Service方法,所有更改都将回滚。因此,将删除数据库内部创建的所有实体。

//entities
@Entity
public class ObjectB{
   @Id
   private long id;
   ...
}

@Entity
public class ObjectC{
   @Id
   private long id;
   ...
}



//servicies
@Service
@Transactional
public class ClassA{

   @Autowired
   private ClassB classB;

   @Autowired
   private ClassC classC;

   public void methodA(){
      classB.insertB(new ObjectB());
      classC.insertC(new ObjectC());
   }
}

@Service
@Transactional
public class ClassB{

   @Autowired
   private RepositoryB repositoryB;

   public void insertB(ObjectB b){
      repositoryB.save(b);
   }
}

@Service
@Transactional
public class ClassC{

   @Autowired
   private RepositoryC repositoryC;

   public void insertC(ObjectC c){
      repositoryC.save(c);
   }
}


//repositories
@Repository
public interface RepositoryB extends CrudRepository<ObjectB, String>{
}

@Repository
public interface RepositoryC extends CrudRepository<ObjectC, String>{
}

我想要ClassA的methodA,一旦从methodB或methodC抛出异常,它就会回滚数据库中的所有更改。 但这并没有做到。例外之后,所有更改都将保留... 我想念什么? 我应该添加什么才能使其按需工作? 我正在使用Spring Boot 2.0.6! 我没有进行任何特别配置以使交易正常进行!


编辑1

这是我的主要课程,如果可以帮助您

@SpringBootApplication
public class JobWebappApplication extends SpringBootServletInitializer {


    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(JobWebappApplication.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(JobWebappApplication.class, args);
    }
}

当引发异常时,这是我在控制台中看到的:

Completing transaction for [com.example.ClassB.insertB]
Retrieved value [org.springframework.orm.jpa.EntityManagerHolder@31d4fbf4] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@df9d400] bound to thread [http-nio-8080-exec-7]
Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder@1d1ad46b] for key [HikariDataSource (HikariPool-1)] bound to thread [http-nio-8080-exec-7]
Getting transaction for [com.example.ClassC.insertC]
Completing transaction for [com.example.ClassC.insertC] after exception: java.lang.RuntimeException: runtime exception!
Applying rules to determine whether transaction should rollback on java.lang.RuntimeException: runtime exception!
Winning rollback rule is: null
No relevant rollback rule found: applying default rules
Completing transaction for [com.example.ClassA.methodA] after exception: java.lang.RuntimeException: runtime exception!
Applying rules to determine whether transaction should rollback on java.lang.RuntimeException: runtime exception!
Winning rollback rule is: null
No relevant rollback rule found: applying default rules
Clearing transaction synchronization
Removed value [org.springframework.jdbc.datasource.ConnectionHolder@1d1ad46b] for key [HikariDataSource (HikariPool-1)] from thread [http-nio-8080-exec-7]
Removed value [org.springframework.orm.jpa.EntityManagerHolder@31d4fbf4] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean@df9d400] from thread [http-nio-8080-exec-7]
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: runtime exception!] with root cause

似乎每次调用一个方法都会创建一个新事务!在RuntimeException发生后没有回滚任何东西!


编辑2

这是pom.xml依赖项文件:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.10.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.5</version>
        </dependency>
</dependencies>

这是application.properties文件:

spring.datasource.url=jdbc:mysql://localhost:3306/exampleDB?useSSL=false
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.show-sql=true
logging.level.org.springframework.transaction=TRACE
spring.jpa.database=MYSQL
spring.jpa.hibernate.ddl-auto=update
spring.datasource.driver.class=com.mysql.jdbc.Driver  
spring.jpa.properties.hibernate.locationId.new_generator_mappings=false

解决方案

感谢@ M.Deinum,我找到了解决方案!

我使用了错误的数据库引擎(MyISAM),该引擎不支持事务!因此,我使用支持事务的“ InnoDB”更改了表引擎类型。我所做的是这样:

  1. 我在application.properties文件中添加了此属性,以便告诉JPA它应用来“操纵”表的引擎类型:
  

spring.jpa.properties.hibernate.dialect =   org.hibernate.dialect.MySQL5InnoDBDialect

  1. 我将所有现有表(具有错误的引擎类型)拖放到了数据库中,并让JPA使用正确的引擎(InnoDB)重新创建了所有表。

现在,所有抛出的RuntimeExceptions都会使事务回滚其中进行的所有更改。

ALERT:我注意到,如果抛出不是RuntimeException子类的异常,则不会应用回滚,并且所有已完成的更改都将保留在数据库中。

3 个答案:

答案 0 :(得分:4)

您要实现的目标应该可以立即使用。检查您的弹簧配置。

确保创建了TransactionManager bean,并确保在春天的某些@Configuration上放置了@EnableTransactionManagement注释。该注释负责注册必要的Spring组件,这些组件可为注释驱动的事务管理提供支持,例如TransactionInterceptor以及基于@Transactional方法时将拦截器编织到调用堆栈中的基于代理或基于AspectJ的建议被调用。

请参阅链接的文档。

如果您使用的是spring-boot,并且您在类路径上有PlatformTransactionManager类,则应该automatically为您添加此注释。

此外,请注意,已检查的异常不会触发交易回滚。只有运行时异常和错误才会触发回滚。当然,您可以使用rollbackFornoRollbackFor注释参数配置此行为。

修改

正如您所澄清的那样,您正在使用spring-boot,答案是:所有人都应该在没有任何配置的情况下工作。

以下是弹簧启动版本2.1.3.RELEASE的100%工作示例(但应与任何版本的c一起使用):

依赖项:

    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    runtimeOnly('com.h2database:h2') // or any other SQL DB supported by Hibernate
    compileOnly('org.projectlombok:lombok') // for getters, setters, toString

用户实体:

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
@Getter
@Setter
@ToString
public class User {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;
}

图书实体:

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;

@Entity
@Getter
@Setter
@ToString
public class Book {

    @Id
    @GeneratedValue
    private Integer id;

    @ManyToOne
    private User author;

    private String title;
}

用户存储库:

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Integer> {
}

图书库:

import org.springframework.data.jpa.repository.JpaRepository;

public interface BookRepository extends JpaRepository<Book, Integer> {
}

用户服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Component
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User saveUser(User user) {
//        return userRepository.save(user);
        userRepository.save(user);
        throw new RuntimeException("User not saved");
    }

    public List<User> findAll() {
        return userRepository.findAll();
    }
}

图书服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Component
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    public Book saveBook(Book book) {
        return bookRepository.save(book);
    }

    public List<Book> findAll() {
        return bookRepository.findAll();
    }
}

综合服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Component
public class CompositeService {

    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;

    public void saveUserAndBook() {
        User user = new User();
        user.setName("John Smith");
        user = userService.saveUser(user);

        Book book = new Book();
        book.setAuthor(user);
        book.setTitle("Mr Robot");
        bookService.saveBook(book);
    }
}

主要:

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class JpaMain {

    public static void main(String[] args) {
        new SpringApplicationBuilder(JpaMain.class)
                .web(WebApplicationType.NONE)
                .properties("logging.level.org.springframework.transaction=TRACE")
                .run(args);
    }

    @Bean
    public CommandLineRunner run(CompositeService compositeService, UserService userService, BookService bookService) {
        return args -> {
            try {
                compositeService.saveUserAndBook();
            } catch (RuntimeException e) {
                System.err.println("Exception: " + e);
            }

            System.out.println("All users: " + userService.findAll());
            System.out.println("All books: " + bookService.findAll());
        };
    }
}

如果运行main方法,则应该看到在DB中找不到任何书籍或用户。事务回滚。如果您从throw new RuntimeException("User not saved")中删除了UserService行,则两个实体都会被保存。

您还应该在org.springframework.transaction级别看到TRACE软件包的日志,例如,您将看到:

Getting transaction for [demo.jpa.CompositeService.saveUserAndBook]

然后在引发异常之后:

Completing transaction for [demo.jpa.CompositeService.saveUserAndBook] after exception: java.lang.RuntimeException: User not saved
Applying rules to determine whether transaction should rollback on java.lang.RuntimeException: User not saved
Winning rollback rule is: null
No relevant rollback rule found: applying default rules
Clearing transaction synchronization

此处No relevant rollback rule found: applying default rules表示将应用DefaultTransactionAttribute定义的规则来确定是否应回滚事务。这些规则是:

  

在运行时回滚,但默认情况下不检查异常。

RuntimeException是运行时异常,因此事务将回滚。

Clearing transaction synchronization是实际应用回滚的位置。您还会看到其他一些Applying rules to determine whether transaction should rollback消息,因为@Transactional方法嵌套在这里(UserService.saveUserCompositeService.saveUserAndBook调用,并且两个方法均为@Transactional),但是它们所做的只是确定未来操作的规则(在事务同步点)。在最外面的@Transactional方法出口,实际回滚将只执行一次。

答案 1 :(得分:0)

从spring 3.1开始,如果您在类路径上使用spring-data- *或spring-tx依赖项,则默认情况下将启用事务管理。

https://www.baeldung.com/transaction-configuration-with-jpa-and-spring

但是检查Springs Transactional注释,我们可以看到,如果异常抛出不是RuntimeException的扩展,则需要通知参数rollbackFor。

/**
 * Defines zero (0) or more exception {@link Class classes}, which must be
 * subclasses of {@link Throwable}, indicating which exception types must cause
 * a transaction rollback.
 * <p>By default, a transaction will be rolling back on {@link RuntimeException}
 * and {@link Error} but not on checked exceptions (business exceptions). See
 * {@link org.springframework.transaction.interceptor.DefaultTransactionAttribute#rollbackOn(Throwable)}
 * for a detailed explanation.
 * <p>This is the preferred way to construct a rollback rule (in contrast to
 * {@link #rollbackForClassName}), matching the exception class and its subclasses.
 * <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(Class clazz)}.
 * @see #rollbackForClassName
 * @see org.springframework.transaction.interceptor.DefaultTransactionAttribute#rollbackOn(Throwable)
 */
Class<? extends Throwable>[] rollbackFor() default {};

一个简单的 @Transactional(rollbackFor = Exception.class)应该可以工作

答案 2 :(得分:-2)

您要在这里实现的目标是不可能的,因为一旦执行完该方法,您就会离开该方法。带有@Transactional批注的更改无法还原。

或者,您可以将auto commit设置为false,并在类A的methodA中编写一个try catch块。如果没有异常,则提交DB事务,否则不要这样做。

相关问题