본문 바로가기

Programming!

Spring Boot 에서 다중 Datasource 의 사용. #2

첫번째.


http://eclipse4j.tistory.com/284



Spring Boot / Data / JPA 에서 위와 같이 다중 Datasource를 기본적으로 사용했다면 문제가 없지만, 

만약 QueryDsl을 사용시에는 QuerydslRepositorySupport 부분에서 어떤 EntityManager를 선택해야 하는지 몰라서(?) 오류를 내뱉는다.


QuerydslRepositorySupport.java 

@Repository

public abstract class QuerydslRepositorySupport {


private final PathBuilder<?> builder;


private @Nullable EntityManager entityManager;

private @Nullable Querydsl querydsl;


/**

* Creates a new {@link QuerydslRepositorySupport} instance for the given domain type.

*

* @param domainClass must not be {@literal null}.

*/

public QuerydslRepositorySupport(Class<?> domainClass) {


Assert.notNull(domainClass, "Domain class must not be null!");

this.builder = new PathBuilderFactory().create(domainClass);

}


/**

* Setter to inject {@link EntityManager}.

*

* @param entityManager must not be {@literal null}.

*/

@Autowired

public void setEntityManager(EntityManager entityManager) {


Assert.notNull(entityManager, "EntityManager must not be null!");

this.querydsl = new Querydsl(entityManager, builder);

this.entityManager = entityManager;

}

...



보면 setEntityManager(EntityManager entityManager) { .. 이부분에 Autowired 가 걸려있는 것을 확인 할 수 있다. 저 EntityManager가 과연 다중 Datasource에서 어떤것인지 알 수 있겠는가?

해서 persistentUnit을 지정해줘야 한다. 하지만 QuerydslRepositorySupport 이놈은 제공 소스아니던가...



단순 클래스니까..  QuerydslRepositorySupport 와 동일한 FirstQuerydslRepositorySupport, SecondQuerydslRepositorySupport 로 두개를 분리해서 사용하도록 하자.

...

    @PersistenceContext(unitName = "first")

    public void setEntityManager(EntityManager entityManager) {

        Assert.notNull(entityManager, "EntityManager must not be null!");

        this.querydsl = new Querydsl(entityManager, builder);

        this.entityManager = entityManager;

    }

...