Transaction management with Spring Batch

Dimitri

I am discovering actually Spring and I am able to setup some jobs. Now, I would like to save my imported datas in a database using Hibernate/JPA and I keep getting this error :

14:46:43.500 [main] ERROR o.s.b.core.step.AbstractStep   - Encountered an error executing the step javax.persistence.TransactionRequiredException: no transaction is in progress

I see that the problem is with the transaction. Here is my spring java config for the entityManager and the transactionManager :

 @Configuration
public class PersistenceSpringConfig implements EnvironmentAware
{


    @Bean
  public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws Exception
  {
    // Initializes the entity manager
    LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
    factoryBean.setPersistenceUnitName(PERSISTENCE_UNIT_NAME);
    factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
    factoryBean.setDataSource(dataSource());

    // Scans the database model
    factoryBean.setPackagesToScan(EntiteJuridiqueJPA.class.getPackage().getName());

    // Defines the Hibernate properties
    Properties jpaProperties = new Properties();
    jpaProperties.setProperty("hibernate.show_sql", "false");
    jpaProperties.setProperty("hibernate.format_sql", "false");
    String connectionURL = "jdbc:h2:file:" + getDatabaseLocation();
    jpaProperties.setProperty("hibernate.connection.url", connectionURL);
    jpaProperties.setProperty("hibernate.connection.username", "sa");
    jpaProperties.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    jpaProperties.setProperty("hibernate.dialect", H2Dialect.class.getName());
    jpaProperties.setProperty("hibernate.hbm2ddl.auto", "create");
    jpaProperties.setProperty("hibernate.hbm2ddl.import_files_sql_extractor", "org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor");
    jpaProperties.setProperty("hibernate.hbm2ddl.import_files",
        "org/springframework/batch/core/schema-drop-h2.sql,org/springframework/batch/core/schema-h2.sql");

    factoryBean.setJpaProperties(jpaProperties);
    return factoryBean;
  }



 @Bean
  public PlatformTransactionManager transactionManager2() throws Exception
  {
    EntityManagerFactory object = entityManagerFactory().getObject();
    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(object);
    return jpaTransactionManager;
  }

I am using the JpaItemWriter to store the datas in the database :

 @Bean
  public ItemWriter<EntiteJuridiqueJPA> writer()
  {
    JpaItemWriter<EntiteJuridiqueJPA> writer = new JpaItemWriter<EntiteJuridiqueJPA>();    
    writer.setEntityManagerFactory(entityManagerFactory.getObject());
    return writer;
  }

This is the code that causes the exception : javax.persistence.TransactionRequiredException: no transaction is in progress

Any idea to how to solve this problem?

[Edit] I am putting also the Job definition and the step definition. All my Spring configuration is written in Java.

 @Configuration
@EnableBatchProcessing
@Import(PersistenceSpringConfig.class)
public class BatchSpringConfig
{
  @Autowired
  private JobBuilderFactory  jobBuilders;

  @Autowired
  private StepBuilderFactory stepBuilders;

  @Autowired
  private DataSource         dataSource;

  @Autowired
  private LocalContainerEntityManagerFactoryBean entityManagerFactory;

  @Bean
  public Step step()
  {
    return stepBuilders.get("step").<EntiteJuridique, EntiteJuridiqueJPA> chunk(5).reader(cvsReader(null))
        .processor(processor()).writer(writer()).listener(processListener()).build();
  }

  @Bean
  @StepScope
  public FlatFileItemReader<EntiteJuridique> cvsReader(@Value("#{jobParameters[input]}") String input)
  {
    FlatFileItemReader<EntiteJuridique> flatFileReader = new FlatFileItemReader<EntiteJuridique>();
    flatFileReader.setLineMapper(lineMapper());
    flatFileReader.setResource(new ClassPathResource(input));
    return flatFileReader;
  }

  @Bean
  public LineMapper<EntiteJuridique> lineMapper()
  {
    DefaultLineMapper<EntiteJuridique> lineMapper = new DefaultLineMapper<EntiteJuridique>();
    DelimitedLineTokenizer lineTokenizer = new DelimitedLineTokenizer();
    lineTokenizer.setDelimiter(";");
    lineTokenizer.setNames(new String[] { "MEGA_ENTITE", "PORTEFEUILLE", "MEGA_ENTITE", "Libellé" });

    BeanWrapperFieldSetMapper<EntiteJuridique> fieldSetMapper = new BeanWrapperFieldSetMapper<EntiteJuridique>();
    fieldSetMapper.setTargetType(EntiteJuridique.class);

    lineMapper.setLineTokenizer(lineTokenizer);
    lineMapper.setFieldSetMapper(fieldSetMapper);

    return lineMapper;
  }

  @Bean
  public Job dataInitializer()
  {
    return jobBuilders.get("dataInitializer").listener(protocolListener()).start(step()).build();
  }

  @Bean
  public ItemProcessor<EntiteJuridique, EntiteJuridiqueJPA> processor()
  {
    return new EntiteJuridiqueProcessor();
  }

  @Bean
  public ItemWriter<EntiteJuridiqueJPA> writer()
  {
    JpaItemWriter<EntiteJuridiqueJPA> writer = new JpaItemWriter<EntiteJuridiqueJPA>();    
    writer.setEntityManagerFactory(entityManagerFactory.getObject());
    return writer;
    // return new EntiteJuridiqueWriter();
  }

  @Bean
  public ProtocolListener protocolListener()
  {
    return new ProtocolListener();
  }

  @Bean
  public CSVProcessListener processListener()
  {
    return new CSVProcessListener();
  }

  @Bean
  public PlatformTransactionManager transactionManager2() throws Exception
  {
    EntityManagerFactory object = entityManagerFactory.getObject();
    JpaTransactionManager jpaTransactionManager = new JpaTransactionManager(object);
    return jpaTransactionManager;
  }

[EDIT] I am still stuck with this problem. I have followed the suggestions of @Sean Patrick Floyd and @bellabax by setting a transaction manager for the stepBuilders, but I still get the same exception. I have tested my entityManager independtly of spring-batch and I am able to store any data in the database.

But, when using the same entity manager with spring batch, I have this exception.

Anyone can give more insights how transactions are managed within spring batch? Thx for your help?

Tobias Flohre

The problem is that you are creating a second transaction manager (transactionManager2), but Spring Batch is using another transaction manager for starting transactions. If you use @EnableBatchProcessing, Spring Batch automatically registers a transaction manager to use for its transactions, and your JpaTransactionManager never gets used. If you want to change the transaction manager that Spring Batch uses for transactions, you have to implement the interface BatchConfigurer. Take a look at this example: https://github.com/codecentric/spring-batch-javaconfig/blob/master/src/main/java/de/codecentric/batch/configuration/WebsphereInfrastructureConfiguration.java. Here I am switching the transaction manager to a WebspherUowTransactionManager, and in the same way you can switch the transaction manager to some other transaction manager. Here's the link to the blog post explaining it: http://blog.codecentric.de/en/2013/06/spring-batch-2-2-javaconfig-part-3-profiles-and-environments/

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Spring Transaction Management @Transactional Behavior

分類Dev

Hibernate Envers Performance and Transaction Management in a Spring Application

分類Dev

Spring Declarative transaction management with hibernate using @Transactional

分類Dev

Test transaction management in TokuMX

分類Dev

削除ステートメント後のSpring Transaction Management Rollback

分類Dev

Spring Hibernate Transaction Logging

分類Dev

Domain driven design - database transaction management

分類Dev

WSO2 Data Services Transaction Management

分類Dev

The Transaction Ended In The Trigger The Batch Has Been Aborted

分類Dev

Spring Transaction Managementでカスタムロールバックメソッドを呼び出す方法は?

分類Dev

Spring Change Transaction Isolation Mode

分類Dev

Propagate spring transaction to sibling call

分類Dev

Spring Batch + Spring Boot + Couchbase

分類Dev

CallableTaskletAdapter Spring Batch

分類Dev

Spring Batch Writer

分類Dev

Spring Batch FlatFile Formatting

分類Dev

Spring Batch MultiLineItemReader with MultiResourcePartitioner

分類Dev

Spring Batch : custom ItemReader

分類Dev

Spring Boot + Spring Batch + Spring JPA

分類Dev

Exception The transaction ended in the trigger. The batch has been aborted

分類Dev

Spring Batch Slow Write and Read

分類Dev

Spring Batch Beanの配置

分類Dev

spring-boot-batch with mongodb

分類Dev

Spring batch parsing on different data

分類Dev

Spring transaction configuration minus Exception (`-Exception`) meaning

分類Dev

Spring JPA transaction over multiple methods

分類Dev

Spring + HibernateTemplate + AOP for transaction mamangement not working

分類Dev

Spring Boot Data Hibernate Transaction Manager

分類Dev

How to handle nested transaction exception in spring integration

Related 関連記事

  1. 1

    Spring Transaction Management @Transactional Behavior

  2. 2

    Hibernate Envers Performance and Transaction Management in a Spring Application

  3. 3

    Spring Declarative transaction management with hibernate using @Transactional

  4. 4

    Test transaction management in TokuMX

  5. 5

    削除ステートメント後のSpring Transaction Management Rollback

  6. 6

    Spring Hibernate Transaction Logging

  7. 7

    Domain driven design - database transaction management

  8. 8

    WSO2 Data Services Transaction Management

  9. 9

    The Transaction Ended In The Trigger The Batch Has Been Aborted

  10. 10

    Spring Transaction Managementでカスタムロールバックメソッドを呼び出す方法は?

  11. 11

    Spring Change Transaction Isolation Mode

  12. 12

    Propagate spring transaction to sibling call

  13. 13

    Spring Batch + Spring Boot + Couchbase

  14. 14

    CallableTaskletAdapter Spring Batch

  15. 15

    Spring Batch Writer

  16. 16

    Spring Batch FlatFile Formatting

  17. 17

    Spring Batch MultiLineItemReader with MultiResourcePartitioner

  18. 18

    Spring Batch : custom ItemReader

  19. 19

    Spring Boot + Spring Batch + Spring JPA

  20. 20

    Exception The transaction ended in the trigger. The batch has been aborted

  21. 21

    Spring Batch Slow Write and Read

  22. 22

    Spring Batch Beanの配置

  23. 23

    spring-boot-batch with mongodb

  24. 24

    Spring batch parsing on different data

  25. 25

    Spring transaction configuration minus Exception (`-Exception`) meaning

  26. 26

    Spring JPA transaction over multiple methods

  27. 27

    Spring + HibernateTemplate + AOP for transaction mamangement not working

  28. 28

    Spring Boot Data Hibernate Transaction Manager

  29. 29

    How to handle nested transaction exception in spring integration

ホットタグ

アーカイブ