在定义多个@EnableJpaRepositories类

时间:2017-09-12 09:00:14

标签: spring spring-data spring-data-jpa

我正在研究Spring Data JPA的用法。感谢是否可以帮助检查哪里出错。

我在2个不同的包中创建了2个JPA存储库:APIRepositoryClientRepository,还创建了2个配置类,分别使用@EnableJpaRepositories注释配置这2个存储库。

当Spring应用程序调用这两个存储库时#39;同时save()个方法,APIRepository.save()将失败,但无一例外。如果移动@Primiary注释(这是为了避免NoUniqueBeanDefinitionException)到APIAppConfig类,ClientRepository.save将无故失败。我打开了SQL日志,没有为失败的方法执行更新SQL。

是不是有人遇到过这样的情况?如何使用Spring Data Jpa?

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);
    }
}

1 个答案:

答案 0 :(得分:0)

在您设置的APIAppConfig课程中

@EnableJpaRepositories(
    basePackages = "test.api.repository", 

但您的APIRepository位于test.api包中,而不在test.api.repository中,至少我在您的APIRepository类源代码中可以看到。

因此,要么更改basePackages值以反映正确的值,要么将APIRepository移到test.api.repository包中