EntityManager를 사용하여 여러 데이터 소스를 봄 부팅
INFOQ의 이 튜토리얼을 사용하여 여러 데이터 소스로 Springboot(v2.0.0.BUILD-SNAPSHOT) 프로젝트를 설정하려고 합니다.
https://www.infoq.com/articles/Multiple-Databases-with-Spring-Boot
그러나 JdbcTemplate 대신 여러 EntityManager를 사용해야 합니다.
제가 지금까지 가지고 있는 것은 다음과 같습니다.
Application.properties
spring.primary.url=jdbc:sqlserver://localhost:2433;databaseName=TEST
spring.primary.username=root
spring.primary.password=root
spring.primary.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.secondary.url=jdbc:oracle:thin:@//localhost:1521/DB
spring.secondary.username=oracle
spring.secondary.password=root
spring.secondary.driverClassName=oracle.jdbc.OracleDriver
어플.자바
package com.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
응용 프로그램 구성.자바
package com.test.config;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class ApplicationConfiguration {
@Primary
@Bean(name = "primaryDB")
@ConfigurationProperties(prefix = "spring.primary")
public DataSource postgresDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "primaryEM")
public LocalContainerEntityManagerFactoryBean storingEntityManagerFactory(
EntityManagerFactoryBuilder builder, @Qualifier("primaryDB") DataSource ds) {
return builder
.dataSource(ds)
.packages("com.test.supplier1")
.persistenceUnit("primaryPU")
.build();
}
@Bean(name = "secondaryDB")
@ConfigurationProperties(prefix = "spring.secondary")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryEM")
public LocalContainerEntityManagerFactoryBean storingEntityManagerFactory(
EntityManagerFactoryBuilder builder, @Qualifier("secondaryDB") DataSource ds) {
return builder
.dataSource(ds)
.packages("com.test.supplier2")
.persistenceUnit("secondaryPU")
.build();
}
}
일반 DAO.java
public abstract class GenericDAO<T extends Serializable> {
private Class<T> clazz = null;
@PersistenceContext
protected EntityManager entityManager;
public void setClazz(Class<T> clazzToSet) {
this.clazz = clazzToSet;
}
public T findOne(Integer id) {
return this.entityManager.find(this.clazz, id);
}
public List<T> findAll() {
return this.entityManager.createQuery("from " + this.clazz.getName()).getResultList();
}
@Transactional
public void save(T entity) {
this.entityManager.persist(setModifiedAt(entity));
}
}
Person DAO.java
@Repository
@PersistenceContext(name = "primaryEM")
public class PersonDAO extends GenericDAO<Person> {
public PersonDAO() {
this.setClazz(Person.class);
}
}
제품 DAO.java
@Repository
@PersistenceContext(name = "secondaryEM")
public class ProductDAO extends GenericDAO<Product> {
public ProductDAO() {
this.setClazz(Product.class);
}
}
테스트 서비스.자바
@Service
public class TestService {
@Autowired
PersonDAO personDao;
@Autowired
ProductDAO productDao;
// This should write to primary datasource
public void savePerson(Person person) {
personDao.save(person);
}
// This should write to secondary datasource
public void saveProduct(Product product) {
productDao.save(product);
}
}
문제는 그것이 작동하지 않는다는 것입니다."제품"(2차 ds)을 유지하려고 하면 @Primary 데이터 소스에도 유지하려고 합니다.
기사의 JdbcTemplate 예제와 유사한 작업을 수행하려면 어떻게 해야 합니까?
내가 뭘 잘못하고 있는 거지?
감사합니다!
업데이트(@Deepak 솔루션 사용)
아래 항목을 사용해 보십시오.
@Repository
public class PersonDAO extends GenericDAO<Person> {
@Autowired
public PersonDAO(@Qualifier("primaryEM") EntityManager entityManager) {
this.entityManager = entityManager;
this.setClazz(Person.class);
}
}
제품 DAO
@Repository
public class ProductDAO extends GenericDAO<Product> {
@Autowired
public ProductDAO(@Qualifier("secondaryEM") EntityManager entityManager) {
this.entityManager = entityManager;
this.setClazz(Product.class);
}
}
또한 GenericD에서 @PersistenceContext 주석 제거AO
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.BUILD-SNAPSHOT)
com.test.Application : Starting Application on...
com.test.Application : No active profile set, falling back to default profiles: default
ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@69b2283a: startup date [Thu Apr 20 15:28:59 BRT 2017]; root of context hierarchy
.s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
.s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
o.apache.catalina.core.StandardService : Starting service Tomcat
org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.12
o.a.c.c.C.[Tomcat].[localhost].[/ : Initializing Spring embedded WebApplicationContext
o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4001 ms
o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'primaryPU'
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: primaryPU ...]
org.hibernate.Version : HHH000412: Hibernate Core {5.2.9.Final}
org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect
j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'primaryPU'
j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'secondaryPU'
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ name: secondaryPU ...]
org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.SQLServer2012Dialect
j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'secondaryPU'
s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@69b2283a: startup date [Thu Apr 20 15:28:59 BRT 2017]; root of context hierarchy
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/** onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/** onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
s.a.ScheduledAnnotationBeanPostProcessor : No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http)
io.test.Application : Started Application in 76.21 seconds (JVM running for 77.544)
org.hibernate.SQL : select next value for SEQ_TDAI_ID
o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 923, SQLState: 42000
o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00923: FROM keyword not found where expected
--> ERROR
@Primary 데이터 소스 방언(이 경우 "SQL Server 2012 Dialect")을 사용하여 두 엔티티를 모두 구축하는 것 같습니다.
보조 엔터티 관리자는 "Oracle12cDialect"여야 합니다.
업데이트(솔루션)
연결이 정상인 것처럼 보이지만 문제는 잘못된 방언(기본 데이터 소스 방언으로 표시됨)입니다. 따라서 해결책은 EntityManagerFactory에 강제로 적용하는 것입니다. 여기에 제 빠른 수정이 있습니다.
올바른 방언을 덧붙입니다.application.properties
파일
spring.primary.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
spring.secondary.hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
application.properties 방언 값을 다음으로 가져옵니다.ApplicationConfiguration.java
@Value("${spring.primary.hibernate.dialect}")
private String dialect;
EntityManagerFactory에 강제 적용
@Bean(name = "primaryEM")
public LocalContainerEntityManagerFactoryBean storingEntityManagerFactory(
EntityManagerFactoryBuilder builder, @Qualifier("primaryDB") DataSource ds) {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", dialect);
LocalContainerEntityManagerFactoryBean emf = builder
.dataSource(ds)
.packages("com.test.supplier1")
.persistenceUnit("primaryPU")
.build();
emf.setJpaProperties(properties);
return emf;
}
이제 효과가 있습니다.
이것을 하는 더 우아한 방법이 있습니까?
아래 항목을 사용해 보십시오.
@Repository
public class PersonDAO extends GenericDAO<Person> {
@Autowired
public PersonDAO(@Qualifier("primaryEM") EntityManager entityManager) {
this.entityManager = entityManager;
this.setClazz(Person.class);
}
}
제품 DAO
@Repository
public class ProductDAO extends GenericDAO<Product> {
@Autowired
public ProductDAO(@Qualifier("secondaryEM") EntityManager entityManager) {
this.entityManager = entityManager;
this.setClazz(Product.class);
}
}
또한 GenericD에서 @PersistenceContext 주석 제거AO
지속성 단위를 지정하려면 "@PersistenceContext(이름 = "secondaryEM")"를 "@PersistenceContext(unitName = "secondaryEM")"로 변경해야 한다고 생각합니다.
이것은 나에게 도움이 됩니다.
application.properties
app.hibernate.primary.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
app.hibernate.secondary.hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
hibernate.hbm2dl과 같이 주 속성에 8번, 보조 속성에 8번 더 추가할 수 있습니다.자동, 최대 절전 모드.show_sql 등
응용 프로그램 구성.자바
@Bean("primaryhibernateproperties")
@ConfigurationProperties("app.hibernate.primary")
public Properties primaryHibernateProperties() {
return new Properties();
}
@Bean(name = "primaryEM")
public LocalContainerEntityManagerFactoryBean storingEntityManagerFactory(
EntityManagerFactoryBuilder builder, @Qualifier("primaryDB") DataSource ds) {
LocalContainerEntityManagerFactoryBean emf = builder
.dataSource(ds)
.packages("com.test.supplier1")
.persistenceUnit("primaryPU")
.build();
emf.setJpaProperties(primaryHibernateProperties());
return emf;
}
// same with secondary
제네릭 DAO
public abstract class GenericDAO<T extends Serializable> {
private Class<T> clazz;
private EntityManager entityManger;
public GenericDAO(EntityManager entityManger, Class<T> clazz) {
this.entityManger = entityManager;
this.clazz = clazz;
}
// other codes
}
인물 DAO
@Repository
public class PersonDAO extends GenericDAO<Person> {
@Autowired
public PersonDAO(@Qualifier("primaryEM") EntityManager entityManager) {
super(entityManager, Person.class);
}
}
제품 DAO
@Repository
public class ProductDAO extends GenericDAO<Product> {
@Autowired
public ProductDAO(@Qualifier("secondaryEM") EntityManager entityManager) {
super(entityManager, Product.class);
}
}
언급URL : https://stackoverflow.com/questions/43509145/spring-boot-multiple-data-sources-using-entitymanager
'programing' 카테고리의 다른 글
.NET을 사용하여 16진수 색상 코드에서 색상을 가져오려면 어떻게 해야 합니까? (0) | 2023.07.06 |
---|---|
경로 쿼리 매개 변수 가져오기 (0) | 2023.07.06 |
여러 열에 NVL 사용 - Oracle SQL (0) | 2023.07.06 |
여러 변수를 동시에 선언하는 보다 우아한 방법 (0) | 2023.07.01 |
스프링 부트를 사용하는 동안 동적 속성을 구성하는 방법은 무엇입니까? (0) | 2023.07.01 |