繁体   English   中英

春季启动测试-使用2个数据库时EntityManager不持久

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM