我正在尝试使用Spring数据jpa存储库从springboot应用程序使用多个数据源,并在spring rest controller / service中调用存储库方法,无法调用存储库方法。请在下面找到我的课程并提出适当的解决方案。
// define the service layer to call the repository
public TestService{
@Autowired
private xyRepository xyzRepo;
// Not able to autowire the
xyzRepo.findAll();
//REpository class
public interface xyRepository extends PagingAndSortingRepository<SiteEntity,String>{
{
//call the API method
}
/***Application.properties***/
#production DataBase
spring.datasource.driver-class-name= com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url = jdbc:sqlserver://cdef.com:1435;DatabaseName=tttt
spring.datasource.username = reader
spring.datasource.password = xxxxxxxx
#production DataBase for PGSEO DB
spring.abcdatasource.driver-class-name= com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.abcdatasource.url = jdbc:sqlserver://xyz.com:1436;DatabaseName=abc
spring.abcdatasource.username = xyz
spring.abcdatasource.password = xxxxxx
#spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = false
server.port = 9595
# Naming strategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.hibernate.naming.strategy = org.hibernate.cfg.ImprovedNamingStrategy
#spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.SQLServerDialect
spring.datasource.initialize=false
spring.jpa.hibernate.ddl-auto=false
//1st java config file
package com.sample;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "eoianalyticEntityManager",
transactionManagerRef = "eoianalyticTransactionManager",
basePackages = "com.sample.jparepository.primary" /*** Give the JPA repository location for eoi analytic DB**/
)
public class EOIAnalyticConfig {
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource springDataSource() {
return DataSourceBuilder
.create()
.build();
}
/**
* Entity manager definition.
*
* @param builder an EntityManagerFactoryBuilder.
* @return LocalContainerEntityManagerFactoryBean.
*/
@Primary
@Bean(name = "eoianalyticEntityManager")
public LocalContainerEntityManagerFactoryBean eoianalyticEntityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(springDataSource())
.properties(hibernateProperties())
.packages("com.sample.entity.primary")
.persistenceUnit("eoianalyticpu")
.build();
}
@Primary
@Bean(name = "eoianalyticTransactionManager")
public PlatformTransactionManager eoianalyticTransactionManager(@Qualifier("eoianalyticEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
private Map<String, Object> hibernateProperties() {
Resource resource = new ClassPathResource("application.properties");
try {
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
return properties.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue())
);
} catch (IOException e) {
return new HashMap<String, Object>();
}
}
}
//2nd config file for second datasource
package com.sample;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "abcEntityManager",
transactionManagerRef = "pgseoTransactionManager",
basePackages = "com.sample.jparepository.secondary"/**** Provide the secondary repository package name*******/
)
public class PGSEOConfig {
/**
* PGSEO datasource definition.
*
* @return datasource.
*/
@Bean
@ConfigurationProperties(prefix = "spring.abcdatasource")
public DataSource pgseoDataSource() {
return DataSourceBuilder
.create()
.build();
}
/**
* Entity manager definition.
*
* @param builder an EntityManagerFactoryBuilder.
* @return LocalContainerEntityManagerFactoryBean.
*/
@Bean(name = "pgseoEntityManager")
public LocalContainerEntityManagerFactoryBean pgseoEntityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(pgseoDataSource())
.properties(hibernateProperties())
.packages("com.sample.entity.secondary")
.persistenceUnit("pgseoPU")
.build();
}
/**
* @param entityManagerFactory
* @return
*/
@Bean(name = "pgseoTransactionManager")
public PlatformTransactionManager pgseoTransactionManager(@Qualifier("pgseoEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
private Map<String, Object> hibernateProperties() {
Resource resource = new ClassPathResource("config/"+"application.properties");
try {
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
return properties.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue())
);
} catch (IOException e) {
return new HashMap<String, Object>();
}
}
}
---------------------------------------------------------
//POM.xml file
package com.sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages=("com.sample.*"))
@EntityScan(basePackages = ("com.sample.entity.*"))
@EnableAutoConfiguration
public class MultipleDataSourceApplication {
public static void main(String[] args) {
SpringApplication.run(MultipleDataSourceApplication.class, args);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>MultipleDataSource</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4-4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>