我有一个spring批处理程序,该程序可以成功启动尝试使用HibernateItemWriter将数据写入SQL数据库的作业。但是,休眠代码失败,因为事务从未启动:
org.hibernate.HibernateException: contains is not valid without active transaction
我配置了一个HibernateTransactionManager,我以为应该解决这个问题,但是问题仍然存在。也许我的春季批处理配置仍然关闭?这是配置文件中的相关代码:
BatchConfig.java
@Configuration
@EnableBatchProcessing
@EnableTransactionManagement
public class BatchConfig {
@Bean
public LocalSessionFactoryBean sessionFactory(){
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setAnnotatedClasses(Student.class);
sessionFactory.setHibernateProperties(getProperties());
try {
sessionFactory.afterPropertiesSet();
} catch (IOException e) {
e.printStackTrace();
}
return sessionFactory.getObject();
}
@Bean
public HibernateTransactionManager transactionManager() {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory());
transactionManager.setDataSource(dataSource());
return transactionManager;
}
@Bean
public ItemWriter<Student> studentItemWriter() {
HibernateItemWriter<Student> writer = new HibernateItemWriter<Student>();
writer.setSessionFactory(sessionFactory());
return writer;
}
}
答案 0 :(得分:0)
我配置了一个HibernateTransactionManager,我以为应该解决这个问题,但是问题仍然存在。也许我的春季批处理配置仍然关闭?
在应用程序上下文中仅将HibernateTransactionManager
声明为bean,Spring Batch将不会使用它。您需要扩展DefaultBatchConfigurer
并覆盖getTransactionManager
。在您的情况下,应该是这样的:
@Configuration
@EnableBatchProcessing
@EnableTransactionManagement
public class BatchConfig {
@Override
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory());
transactionManager.setDataSource(dataSource());
return transactionManager;
}
}
有关如何自定义Spring Batch所需的基础结构bean的更多详细信息,请参考reference documentation。