@DataJpaTest 如何指定要扫描的存储库和实体 [英] @DataJpaTest how to specify repositories and entities to scan
问题描述
默认@DataJpaTest
扫描所有jpa 存储库和@Entity
.就我而言,我有 5 个存储库包和 5 个实体包.例如
By default @DataJpaTest
scans all jpa repositories and @Entity
. In my case I have 5 repositories package and 5 entities package. E.g
com.acme.product.entity
与com.acme.product.repository
com.acme.users.entity
与com.acme.users.repository
com.acme.client.entity
与com.acme.client.repository
等等......
我想在单独的课程中测试每个部分.例如
I would like to test each part in a separate classe. E.g.
@RunWith(SpringRunner.class)
@DataJpaTest
//Some configurations to import only product repositories and product entities
public class TestProductRepository {
@Autowired
TestEntityManager entityManager;
}
请注意,我已经配置了 5 个不同的 EntityManager
我想导入它们并使用例如 TestProductRepository
中的 productEntityManager
而不是默认 TestEntityManager
加载所有存储库/实体.
Note that I have configured 5 different EntityManager
I would like to import them and use for example the productEntityManager
in the TestProductRepository
instead of the default TestEntityManager
which loads all repositories/entites.
非常感谢
推荐答案
这就是我设法实现我想要的:
This is how I manage to achieve what I wanted:
@ActiveProfiles( "dev" )
@RunWith( SpringRunner.class )
@DataJpaTest
// Exclude the default test database + the default EntityManager in purpose to use my configurations instead.
@AutoConfigureTestDatabase( connection = H2, replace = AutoConfigureTestDatabase.Replace.AUTO_CONFIGURED )
@Import( {
ProductDataBaseConfig.class,//Import ProductEntityManager and other beans related to DB operations like TransactionManager, etc...
ProductRepositoryContainer.class //Custom bean containing all product repositories
} )
public class TestProductRepository {
@Autowired
private TestEntityManager entityManager;
}
这里重要的是 @AutoConfigureTestDatabase(...)
和 @Import(...)
,因为我替换了自动配置的 bean 并导入了我自己的 ProductEntityManager
TestEntityManager
使用提供的配置.这也减少了 @DataJpaTest
的范围,它不会扫描类路径中的所有实体和存储库,这正是我想要的.
The important thing here is the @AutoConfigureTestDatabase(...)
and @Import(...)
, as I replaced the autoconfigured beans and import my own ProductEntityManager
the TestEntityManager
uses that provided configuration.
This also reduce the scope of @DataJpaTest
which does not scan all entities and repositories in the classpath and that was what I wanted.
这篇关于@DataJpaTest 如何指定要扫描的存储库和实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!