Spring启动测试 - 使用2个数据库时EntityManager不会保留

Jus*_*tas 0 java spring hibernate spring-boot spring-boot-test

我有控制器的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
    }
} 
Run Code Online (Sandbox Code Playgroud)

我有两个数据库配置:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "primaryManagerFactory", basePackages = { "com.example.repository.primary" })
public class PrimaryDbConfig {
Run Code Online (Sandbox Code Playgroud)

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "anotherManagerFactory", basePackages = { "com.example.repository.another" })
public class AnotherDbConfig {
Run Code Online (Sandbox Code Playgroud)

测试属性片段:

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
Run Code Online (Sandbox Code Playgroud)

GenericDAOImpl片段:

@PersistenceContext(unitName = "another-persistence-unit")
protected EntityManager entityManager;

@Override
@Transactional
public void save(T entity) {
    entityManager.persist(entity);
}
Run Code Online (Sandbox Code Playgroud)

当我运行test时,exampleDAO.save(someEntity)方法不会将任何SQL保存或输出到日志.exampleDAO不是主要数据源.

如果我改为:

@Override
@Transactional
public void save(T entity) {
    entityManager.unwrap(Session.class).save(entity);
}
Run Code Online (Sandbox Code Playgroud)

它运作良好并且持久化数据.但是,与主数据源DAO相同的方法会使实体持久化EntityManager.

为什么要保存实体Session但不保存EntityManager

And*_*nyk 5

如果使用两个DB,则应创建并指定单独的TransactionManager-s

@Override
@Transactional("transactionManagerName")
public void save(T entity) {
   entityManager.persist(entity);
}
Run Code Online (Sandbox Code Playgroud)