我正在研究Spring Data JPA的用法。感谢是否可以帮助检查哪里出错。
我在2个不同的包中创建了2个JPA存储库:APIRepository
和ClientRepository
,还创建了2个配置类,分别使用@EnableJpaRepositories
注释配置这2个存储库。
当Spring应用程序调用这两个存储库时#39;同时save()
个方法,APIRepository.save()
将失败,但无一例外。如果移动@Primiary
注释(这是为了避免NoUniqueBeanDefinitionException
)到APIAppConfig
类,ClientRepository.save
将无故失败。我打开了SQL日志,没有为失败的方法执行更新SQL。
APIRepository
package test.api;
public interface APIRepository extends Repository<API, Long>{
....
}
APIAppConfig
package test.api;
@Configuration
@ComponentScan(basePackages = "test.api")
@EnableJpaRepositories(
basePackages = "test.api.repository",
entityManagerFactoryRef = "apiEntityManagerFactory",
transactionManagerRef="apiTransactionManager",
enableDefaultTransactions=true
)
@EnableTransactionManagement
public class APIAppConfig {
@Bean
public LocalContainerEntityManagerFactoryBean apiEntityManagerFactory(){
...
}
@Bean
public PlatformTransactionManager apiTransactionManager() {
...
}
@Bean
public DataSource apiDataSource() {
...
}
}
APIService
package test.api;
@Service
public class APIService {
@Autowired
private APIRepository apiRepository;
public API findOne(Long id){
return apiRepository.findOne(id);
}
@Transactional("apiTransactionManager")
public void updateOne(API api){
apiRepository.save(api);
}
}
ClientRepository
package test.client;
public interface ClientRepository extends Repository<Client, Long>{
...
}
ClientAppConfig
package test.client;
@Configuration
@ComponentScan(basePackages = "test.client")
@EnableJpaRepositories(
basePackages = "test.client",
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef="transactionManager",
enableDefaultTransactions=true
)
@EnableTransactionManagement
public class ClientAppConfig {
@Bean
@Primary
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
...
}
@Bean
public PlatformTransactionManager transactionManager() {
...
}
@Bean
@Primary
public DataSource dataSource() {
...
}
}
ClientService
package test.client;
@Service
public class ClientService {
@Autowired
private ClientRepository clientRepository;
public DaoTest findOne(Long id){
return clientRepository.findOne(id);
}
@Transactional("transactionManager")
public void updateOne(Client client){
clientRepository.save(client);
}
}
答案 0 :(得分:0)
在您设置的APIAppConfig
课程中
@EnableJpaRepositories(
basePackages = "test.api.repository",
但您的APIRepository
位于test.api
包中,而不在test.api.repository
中,至少我在您的APIRepository
类源代码中可以看到。
因此,要么更改basePackages
值以反映正确的值,要么将APIRepository
移到test.api.repository
包中