我有一个Crud Repository界面
@Repository
public interface SampleRepository extends CrudRepository<Metadata, String> {
findById(UUID id);
}
I am trying to use it in my test class which is in another package
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
@WebAppConfiguration
public class SampleRepositoryTest {
@Autowired
private SampleRepository sampleRepository;
它说没有发现SampleRepository的bean定义。任何人都可以帮助我为什么我不能自动装载这个存储库
答案 0 :(得分:1)
如评论中所述:SampleRepository不需要@Repository。 @WebAppConfiguration对测试也看起来很奇怪。但这两个都没问题。
更重要的是:即使您没有提供TestContext.java文件,它应该是这样的:
@Configuration
// be sure to provide base package where your repostories are located
@EnableJpaRepositories(basePackages = {
"com.acme.repositories"
})
public class TestContext {
// your datasource
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.HSQL).build();
}
// your entity manager factory
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
// your domain classes package
factory.setPackagesToScan("com.acme.domain");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
// your jpa transaction manager
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
}
答案 1 :(得分:0)
没有必要使用@Repository。您的代码应为:
public interface SampleRepository extends CrudRepository<Metadata, String> {
@Query(value = "select * from db.tabel where id = :id", nativeQuery = true)
findById(@Param("id") UUID id);
}