[SPRING] 테스트 컨텍스트에 대한 @Transactional 테스트를 위해 PlatformTransactionManager를 검색하는 데 실패했습니다.
SPRING테스트 컨텍스트에 대한 @Transactional 테스트를 위해 PlatformTransactionManager를 검색하는 데 실패했습니다.
트랜잭션 사이의 Hibernate (버전 4) EHCache의 캐싱 기능을 테스트하려고 할 때 실패합니다 : 테스트 컨텍스트에 대한 @Transactional 테스트를 위해 PlatformTransactionManager를 검색하지 못했습니다.
테스트
@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();
}
}
매뉴얼 방식의 트랜잭션 처리는 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;
}
}
오류
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]]].
어떻게 작동 시키는가?
최신 정보:
@TestExecutionListeners가 실제로 필요한지는 모르겠지만 추가하여 작동하게 만들었습니다.
@Transactional(transactionManager = "hibernateTransactionManager")
@TestExecutionListeners({})
해결법
-
==============================
1.@Transactional은 명시 적으로 지정되지 않은 경우 응용 프로그램 컨텍스트에서 transactionManager라는 이름의 Bean을 필요로합니다. @Transaction 주석 값 속성을 사용하여 테스트에 사용할 트랜잭션 관리자를 지정하십시오.
@Transactional은 명시 적으로 지정되지 않은 경우 응용 프로그램 컨텍스트에서 transactionManager라는 이름의 Bean을 필요로합니다. @Transaction 주석 값 속성을 사용하여 테스트에 사용할 트랜잭션 관리자를 지정하십시오.
예를 들어 hibernateTransactionManager를 사용하려면 다음과 같이 지정하십시오.
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { ApplicationConfig.class, CachingConfig.class }, loader = AnnotationConfigContextLoader.class) @PersistenceContext @Transactional("hibernateTransactionManager") public class EHCacheTest extends AbstractTransactionalJUnit4SpringContextTests { }
그렇지 않으면 사용하려는 트랜잭션 관리자의 이름을 기본 이름 인 transactionManager의 이름으로 변경하십시오.
@Bean public PlatformTransactionManager transactionManager() { // TODO: Really need this? final HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory().getObject()); return transactionManager; }
from https://stackoverflow.com/questions/37344471/failed-to-retrieve-platformtransactionmanager-for-transactional-test-for-test-c by cc-by-sa and MIT license
'SPRING' 카테고리의 다른 글
[SPRING] setBundle을 사용해로드 된 프로퍼티 파일의 재로드 (0) | 2019.04.20 |
---|---|
[SPRING] 스프링 3을 사용하여 프로그래밍 방식으로 HTTP 응답 상태 변경 (0) | 2019.04.20 |
[SPRING] 트랜잭션, JavaConfig에 대해 Hibernate Session을 열 수 없음 (0) | 2019.04.20 |
[SPRING] 스프링의 validator가 데이터베이스에 액세스해야합니까? (0) | 2019.04.20 |
[SPRING] Spring 컨텍스트를 초기화 할 때 org.springframework.asm.ClassReader에서의 IllegalArgumentException (0) | 2019.04.20 |