[英]Spring boot test - EntityManager does not persist when using 2 databases
我對控制器進行了Spring Boot測試:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ExampleTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ExampleDAO;
@Test
public void someTest(){
exampleDAO.save(someEntity);
// call to endpoint
}
}
我有兩個數據庫配置:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "primaryManagerFactory", basePackages = { "com.example.repository.primary" })
public class PrimaryDbConfig {
和
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "anotherManagerFactory", basePackages = { "com.example.repository.another" })
public class AnotherDbConfig {
測試屬性片段:
spring.primary.datasource.url=jdbc:h2:mem:primary;DB_CLOSE_ON_EXIT=FALSE
spring.primary.datasource.username=sa
spring.primary.datasource.password=
spring.primary.datasource.driverClassName=org.h2.Driver
spring.another.datasource.url=jdbc:h2:mem:another;DB_CLOSE_ON_EXIT=FALSE
spring.another.datasource.username=sa
spring.another.datasource.password=
spring.another.datasource.driverClassName=org.h2.Driver
spring.jpa.properties.hibernate.show_sql=true
GenericDAOImpl片段:
@PersistenceContext(unitName = "another-persistence-unit")
protected EntityManager entityManager;
@Override
@Transactional
public void save(T entity) {
entityManager.persist(entity);
}
當我運行測試時, exampleDAO.save(someEntity)
方法不會保存或將任何SQL輸出到日志。 exampleDAO
不是主要數據源。
如果我更改為:
@Override
@Transactional
public void save(T entity) {
entityManager.unwrap(Session.class).save(entity);
}
它可以很好地工作並保留數據。 但是,使用主數據源DAO的相同方法使用EntityManager
保留實體。
為什么它使用Session
保存實體而不使用EntityManager
保存實體?
如果使用兩個數據庫,則應創建並指定單獨的TransactionManager-
@Override
@Transactional("transactionManagerName")
public void save(T entity) {
entityManager.persist(entity);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.