我正在使用Spring及其spring-data-jpa:1.7.0.RELEASE
和hibernate-jpa-2.1-api:1.0.0.Final
。我的数据库是MySQL。在集成测试中,当我保存实体时,entityRepository.save()
方法不返回它的更新版本(例如填充自动递增的id),因此我可以看到它在数据库中。
这是我的配置类:
//@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "core.repository")
@Configuration
@PropertySource("classpath:application.properties")
public class JPAConfiguration {
@Autowired
private Environment env;
private
@Value("${db.driverClassName}")
String driverClassName;
private
@Value("${db.url}")
String url;
private
@Value("${db.username}")
String user;
private
@Value("${db.password}")
String password;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setDatabasePlatform(env.getProperty("hibernate.dialect"));
final LocalContainerEntityManagerFactoryBean em =
new LocalContainerEntityManagerFactoryBean();
em.setJpaVendorAdapter(vendorAdapter);
em.setPackagesToScan(new String[]{"core.persistence"});
em.setDataSource(dataSource());
em.afterPropertiesSet();
return em;
}
@Bean
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
@Bean
public JpaTransactionManager transactionManager(final EntityManagerFactory emf) {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
这是我的考试班:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {JPAConfiguration.class})
//@Transactional
//@TransactionConfiguration(defaultRollback = true)
public class AgencyRepositoryIntegrationTests {
@Autowired
AgencyRepository agencyRepository;
@Test
public void testThatAgencyIsSavedIntoRepoWorks() throws Exception {
Agency c = DomainTestData.getAgency();
Agency d = agencyRepository.save(c);
// here d equals to c but both have id 0.
Collection<Agency> results = Lists.newArrayList(agencyRepository.findAll());
//here results != null and it does contain the agency object.
assertNotNull(results);
}
}
由于研究了stackoverflow中的其他问题,我最终评论了Transactional注释(在测试和配置类中),但它没有用。
由于
答案 0 :(得分:0)
使用saveAndFlush方法确保实体位于数据库中。
如果出现NoTransactionException,请务必将@Transactional添加到您的方法中。
答案 1 :(得分:0)
尝试取消注释@Transactional注释并运行。我无法在您的代码段中看到任何明显的问题,但我内心有一些东西(并且它不是饥饿),说您的交易划分不正确。之前我遇到过类似的问题,只是@transaction注释丢失或交易配置错误。