java 无法为测试上下文的 @Transactional 测试检索 PlatformTransactionManager
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37344471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Failed to retrieve PlatformTransactionManager for @Transactional test for test context
提问by J.Olufsen
Whhen trying to test caching capabilities of Hibernate's (version 4) EHCache between transactions - it fails: Failed to retrieve PlatformTransactionManager for @Transactional test for test context
.
Whhen试图对Hibernate(第4版)交易之间的EHCache测试缓存功能-它失败:Failed to retrieve PlatformTransactionManager for @Transactional test for test context
。
Test
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ApplicationConfig.class, CachingConfig.class }, loader = AnnotationConfigContextLoader.class)
@PersistenceContext
@Transactional
public class EHCacheTest extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
private SessionFactory sessionFactory;
@Test
public void testTransactionCaching(){
Session session = sessionFactory.getCurrentSession();
System.out.println(session.get(CustomerEntity.class, 1));
Query query = session.createQuery("from CustomerEntity where CustomerEntity.customerId<10").setCacheable(true).setCacheRegion("customer");
@SuppressWarnings("unchecked")
List<CustomerEntity> customerEntities = query.list();
System.out.println(customerEntities);
TestTransaction.flagForCommit();
TestTransaction.end();
TestTransaction.start();
Session sessionNew = sessionFactory.getCurrentSession();
System.out.println(sessionNew.get(CustomerEntity.class, 1));
Query anotherQuery = sessionNew.createQuery("from CustomerEntity where CustomerEntity.customerId<10");
anotherQuery.setCacheable(true).setCacheRegion("customer");
@SuppressWarnings("unchecked")
List<CustomerEntity> customerListfromCache = anotherQuery.list();
System.out.println(customerListfromCache);
TestTransaction.flagForCommit();
TestTransaction.end();
}
}
The manual programmatic Transaction handling was implemented the way Spring 4.x suggests in documentation.
手动编程事务处理是按照 Spring 4.x 在文档中建议的方式实现的。
ApplicationConfig
应用配置
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories (basePackages = { "com.hibernate.query.performance.persistence" }, transactionManagerRef = "jpaTransactionManager")
@EnableJpaAuditing
@PropertySource({ "classpath:persistence-postgresql.properties" })
@ComponentScan({ "com.hibernate.query.performance.persistence" })
public class ApplicationConfig {
@Autowired
private Environment env;
public ApplicationConfig() {
super();
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(applicationDataSource());
sessionFactory.setPackagesToScan(new String[] { "com.hibernate.query.performance.persistence.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(applicationDataSource());
emf.setPackagesToScan(new String[] { "com.hibernate.query.performance.persistence.model" });
final JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(vendorAdapter);
emf.setJpaProperties(hibernateProperties());
return emf;
}
@Bean
public DataSource applicationDataSource() {
final BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName")));
dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url")));
dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user")));
dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass")));
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() { // TODO: Really need this?
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
@Bean
public PlatformTransactionManager jpaTransactionManager() { // TODO: Really need this?
final JpaTransactionManager transactionManager = new JpaTransactionManager(); // http://stackoverflow.com/questions/26562787/hibernateexception-couldnt-obtain-transaction-synchronized-session-for-current
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.format_sql", "true");
// hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true");
hibernateProperties.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
// Envers properties
hibernateProperties.setProperty("org.hibernate.envers.audit_table_suffix", env.getProperty("envers.audit_table_suffix")); // TODO: Really need this?
return hibernateProperties;
}
}
CachingConfig
缓存配置
@Configuration
@EnableCaching
public class CachingConfig implements CachingConfigurer {
@Bean(destroyMethod="shutdown")
public net.sf.ehcache.CacheManager ehCacheManager() {
CacheConfiguration cacheConfiguration = new CacheConfiguration();
cacheConfiguration.setName("myCacheName");
cacheConfiguration.setMemoryStoreEvictionPolicy("LRU");
cacheConfiguration.setMaxElementsInMemory(1000);
net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
config.addCache(cacheConfiguration);
return net.sf.ehcache.CacheManager.create(config);
}
@Bean
@Override
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheManager());
}
@Override
public CacheResolver cacheResolver() {
return null;
}
@Bean
@Override
public KeyGenerator keyGenerator() {
return new SimpleKeyGenerator();
}
@Override
public CacheErrorHandler errorHandler() {
return null;
}
}
Error
错误
java.lang.IllegalStateException: Failed to retrieve PlatformTransactionManager for @Transactional test for test context [DefaultTestContext@d8355a8 testClass = EHCacheTest, testInstance = com.hibernate.query.performance.EHCacheTest@3532ec19, testMethod = testTransactionCaching@EHCacheTest, testException = [null], mergedContextConfiguration = [MergedContextConfiguration@59fa1d9b testClass = EHCacheTest, locations = '{}', classes = '{class com.hibernate.query.performance.config.ApplicationConfig, class com.hibernate.query.performance.config.CachingConfig}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextLoader = 'org.springframework.test.context.support.AnnotationConfigContextLoader', parent = [null]]].
How to make it work?
如何使它工作?
Update:
更新:
Made it work by adding, not sure though if @TestExecutionListeners
is really required:
通过添加使其工作,但不确定是否@TestExecutionListeners
真的需要:
@Transactional(transactionManager = "hibernateTransactionManager")
@TestExecutionListeners({})
回答by ekem chitsiga
@Transactional requires a bean with name transactionManager in your application context if not specified explictly. Specify the transaction manager you want to use with your test using the @Transaction annotation value attribute
如果未明确指定,@Transactional 在您的应用程序上下文中需要一个名为 transactionManager 的 bean。使用 @Transaction 注释值属性指定要用于测试的事务管理器
For example if you want to use hibernateTransactionManager specify this as
例如,如果您想使用 hibernateTransactionManager 将其指定为
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ApplicationConfig.class, CachingConfig.class }, loader = AnnotationConfigContextLoader.class)
@PersistenceContext
@Transactional("hibernateTransactionManager")
public class EHCacheTest extends AbstractTransactionalJUnit4SpringContextTests {
}
Otherwise rename the transaction manager you want to use to have the default name transactionManager
否则,将要使用的事务管理器重命名为默认名称 transactionManager
@Bean
public PlatformTransactionManager transactionManager() { // TODO: Really need this?
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}