Spring Batch JpaItemWriter vs HibernateItemWriter and why HibernateTransactionManager is needed when HibernateItemWriter is used

后端 未结 1 839
小蘑菇
小蘑菇 2021-02-09 22:53

I\'m working on Spring Batch with Spring Boot project. My question is, why HibernateTransactionManager and SessionFactory from LocalSessionFactoryBean are needed when I use Hib

相关标签:
1条回答
  • 2021-02-09 23:28

    why HibernateTransactionManager and SessionFactory from LocalSessionFactoryBean are needed when I use HibernateItemWriter

    By default, if you provide a DataSource bean, Spring Batch will use a DataSourceTransactionManager to manage transactions. This transaction manager knows nothing about your JPA/Hibernate context. So the HibernateItemWriter which is using the Hibernate Session behind the scene is not "aware" of the ongoing transaction managed by the DataSourceTransactionManager. Hence the error: no transaction is in progress.

    The HibernateTransactionManager is what makes the Hibernate Session participate in spring managed transactions.

    what is the main difference between JpaItemWriter and HibernateItemWriter?

    The JpaItemWriter use JPA APIs (EntityManagerFactory and EntityManager)to write items. It does not use any JPA provider specific APIs. This makes it possible to switch the JPA provider without changing your writer.

    The HibernateItemWriter on the other side uses Hibernate specific APIs (SessionFactory and Session) and is specific to Hibernate only. This component can be useful for apps using hibernate directly without using JPA. You could have the same writer but for another JPA provider like OpenJpaItemWriter or EclipseLinkItemWriter which use specific APIs from these providers.


    NB: There is a similar question to this one, I'm adding it here for reference: Transaction management with Spring Batch

    0 讨论(0)
提交回复
热议问题