Spring boot test - EntityManager does not persist when using 2 databases

3.3k views Asked by At

I have Spring Boot test for controller:

@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
    }
} 

I have two database configs:

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

And

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

Test properties fragment:

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 fragment:

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

@Override
@Transactional
public void save(T entity) {
    entityManager.persist(entity);
}

When I run test, exampleDAO.save(someEntity) method does not save or output any SQL to logs. exampleDAO is not primary data source.

If I change to:

@Override
@Transactional
public void save(T entity) {
    entityManager.unwrap(Session.class).save(entity);
}

It works well and persists data. However, the same method with primary data source DAO persists entities with EntityManager.

Why does it save entity with Session but not with EntityManager?

1

There are 1 answers

0
Andriy Slobodyanyk On BEST ANSWER

In case of using two DBs separate TransactionManager-s should be created and specified

@Override
@Transactional("transactionManagerName")
public void save(T entity) {
   entityManager.persist(entity);
}