【问题标题】:JPA Transaction - CrudRepository #save(List) not rolled backJPA 事务 - CrudRepository #save(List) 未回滚
【发布时间】:2018-05-17 18:59:24
【问题描述】:

我正在使用带有 spring-boot-starter-data-jpa 和 Camel 2.20.1 的 Spring Boot 1.5.9。 作为输入,我得到一个包含一系列元素的 XML 文件,我使用 JAXB 对其进行解组,然后将它们聚合到一个元素列表中。

为此,我定义了一个 Element 类,在其中我为 JAXB 关联了一个根元素并将其注释为 JPA 实体。

@Entity
@Table (name="tblElement", schema="comp")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Element implements Serializable {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column (name="name")
    @XmlElement(required = true)
    private String name;

    public void Element(){}

    //getter and setter methods
    ...
} 

所以我的骆驼路线会处理我想要存储到 MySQL 数据库(版本:5.1.73)的条目列表。

@Component
public class CompRoute extends RouteBuilder {

    @Autowired
    private ElementDao elementDao;

    @Override
    public void configure() throws Exception {
        DataFormat jaxbDataFormat = new JaxbDataFormat("com.comp.beans");

        from(file:src/test/resources/input)
                .convertBodyTo(byte[].class, "UTF-8")
                .split().tokenizeXML("element") 
                .unmarshal(jaxbDataFormat) 
                .setProperty("SplitSize", simple("${header.CamelSplitSize}"))

                .aggregate(constant(true), new ArrayListAggregationStrategy()) 
                    .completionSize(simple("${property.SplitSize}"))

                .bean(elementDao, "insertElementList");
    }
}

我对 JPA 和事务管理器不是很熟悉,所以我根据这些文档进行了配置:

https://spring.io/guides/gs/accessing-data-jpa/

https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/jpa.repositories.html

application.properties

spring.datasource.url=jdbc:mysql://compserver:3306/comp
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver 

JpaConfig.java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = CompApplication.class)
class JpaConfig {
    @Autowired
    DataSource dataSource;

    @Bean
    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(false);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);

        String entities = ClassUtils.getPackageName(CompApplication.class);
        factory.setPackagesToScan(entities);
        factory.setDataSource(dataSource);
        factory.afterPropertiesSet();

        return factory.getObject();
    }

    @Bean
    @Qualifier (value = "jpaTransactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }
}

CompApplication.java

@SpringBootApplication
public class CompApplication {
  public static void main(String[] args) {
          SpringApplication app = new SpringApplication(CompApplication.class);
          app.setBannerMode(Banner.Mode.OFF);
          app.run(args);
  }

}

ElementDao.java

@Service
public class ElementDao {
    @Autowired
    ElementRepository elementRepository;

    @Transactional (transactionManager = "jpaTransactionManager", readOnly = false, propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void insertElementList(Exchange exchange) {
        if(exchange.getIn().getBody() instanceof List) {
             List<Element> elements= convertListToElementList(exchange.getIn().getBody(List.class));
             if (elements != null) {
                 elementRepository.save(elements);
             }
        }
    }
}

ElementRepository.java

@Repository
public interface ElementRepository extends CrudRepository<Element, Long> {

}

但我的事务配置不正确。因为如果发生错误,例如在存储第 5 个元素时,整个事务不会回滚。它不应该插入任何元素。但是前 4 个元素仍然被存储并提交。

我不明白这种行为?如何设置我的服务#insertElementList 事务性,以便在数据库存储期间发生异常时回滚整个操作?

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>  
     <groupId>com.company</groupId>
     <artifactId>company</artifactId>
     <version>0.0.1</version>
     <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.5.9.RELEASE</version>
     </parent> 
     <properties>
       <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
       <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
       <java.version>1.8</java.version>
       <camel.version>2.20.1</camel.version>
     </properties>
     <dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-jpa</artifactId>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-spring-boot-starter</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jdbc</artifactId>
             <version>${camel.version}</version>
         </dependency>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
             <version>5.1.45</version>
         </dependency>
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jaxb</artifactId>
             <version>2.20.0</version>
         </dependency>    
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-artemis</artifactId>
         </dependency>   
         <dependency>
             <groupId>org.apache.camel</groupId>
             <artifactId>camel-jms</artifactId>
             <version>${camel.version}</version>
         </dependency>   
         <dependency>
             <groupId>com.ibm</groupId>
             <artifactId>com.ibm.mq.allclient</artifactId>
             <version>9.0.0.1</version>
         </dependency>
          <dependency>
             <groupId>net.logstash.logback</groupId>
             <artifactId>logstash-logback-encoder</artifactId>
             <version>4.8</version>
         </dependency>    
         <dependency>
             <groupId>ch.qos.logback</groupId>
             <artifactId>logback-core</artifactId>
             <version>1.1.8</version>
         </dependency>     
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
         </dependency>  
         <dependency>
             <groupId>commons-io</groupId>
             <artifactId>commons-io</artifactId>
             <version>2.5</version>
         </dependency>
     </dependencies>
 </project>

【问题讨论】:

  • 第四条记录是什么意思?你似乎是一次存储所有 ..elementRepository.save(elements);
  • 我测试了它,例如包含 10 个元素的列表,但第 5 个元素将导致 PersistenceException。所以我希望没有记录被保存。但在我的情况下,前 4 个元素仍然被存储。我不明白为什么它没有完全回滚。

标签: java spring transactions spring-data-jpa


【解决方案1】:

我找到了解决方案。问题是数据库而不是我的配置。 MySql 表属于 MyISAM 类型,不支持事务和回滚。所以我将表转换为 InnoDB,现在它可以工作了——当事务失败时,一切都回滚了。

【讨论】:

    【解决方案2】:

    根据 Spring 文档。

    @Transactional 在定义它的同一应用程序上下文中的 bean 上。这意味着,如果您将注释放在 DispatcherServlet 的 WebApplicationContext 中,它只会检查控制器中的 @Transactional bean,而不是您的服务。

    所以,你的保存方法不是事务性的,包括那个包也 保存方法已定义。

    【讨论】:

    • 感谢您的回复。但我很抱歉,我不明白解决方案。我应该在哪里包含哪个包?
    猜你喜欢
    • 2011-02-06
    • 2018-08-15
    • 2015-10-25
    • 2015-05-31
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 2018-08-07
    相关资源
    最近更新 更多