gpt4 book ai didi

java - Spring boot 测试 - 使用 2 个数据库时 EntityManager 不持久

转载 作者:行者123 更新时间:2023-12-01 16:47:57 29 4
gpt4 key购买 nike

我对 Controller 进行了 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);
}

关于java - Spring boot 测试 - 使用 2 个数据库时 EntityManager 不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46274468/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com