๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Spring

SpringBoot Multi DataSource - JPA

by ์ฃผ๋ฐœ2 2023. 1. 21.
๋ฐ˜์‘ํ˜•

๐Ÿ”— SpringBoot์—์„œ ๋ฉ€ํ‹ฐ ๋ฐ์ดํ„ฐ์†Œ์Šค ์„ค์ •ํ•˜๊ธฐ - JPA

ํ•˜๋‚˜์˜ ํ”„๋กœ์ ํŠธ์—์„œ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋‹ค๋ฅธ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋Š”๋ฐ์š”, ์ด๋Ÿฐ ๊ฒฝ์šฐ DataSource๋ฅผ ์ปค์Šคํ…€์œผ๋กœ ์„ค์ •ํ•˜์—ฌ ๊ด€๋ฆฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๊ฐ„๋‹จํ•œ ์„ค์ •์„ ํ†ตํ•ด ํ•œ ํ”„๋กœ์ ํŠธ์—์„œ ๋‹ค๋ฅธ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์ •๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

์˜ˆ์ œ ์ฝ”๋“œ๋Š” GitHub์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

 

๐ŸŽˆ application.yml

yml ํŒŒ์ผ์— ๋‘ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค(datasource, datasource-second)๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.

(๊ธฐ๋ณธ ์Šคํ”„๋ง ๋ถ€ํŠธ์˜ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์„ค์ •๊ณผ ๋‹ฌ๋ฆฌ ๋ฉ€ํ‹ฐ ๋ฐ์ดํ„ฐ ์†Œ์Šค HikariConfig์—์„œ๋Š” url์ด ์•„๋‹Œ jdbc-url์œผ๋กœ ๋„ค์ด๋ฐ์„ ํ•ด์•ผํ•ฉ๋‹ˆ๋‹ค.)

 

 

์ถœ์ฒ˜: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto.data-access.configure-custom-datasource

 

 

๐ŸŽˆ DataSource Configuration 

์•„๋ž˜ ์ฝ”๋“œ์—์„œ ์‚ฌ์šฉํ•  ํŒจํ‚ค์ง€๋ช…์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

  •  User Entity: package com.example.springmultidatasourcejpa.user.entity
  •  User Repository: package com.example.springmultidatasourcejpa.user.repository
  •  Product Entity: package com.example.springmultidatasourcejpa.product.entity
  •  Product Repository: package com.example.springmultidatasourcejpa.product.repository

 

UserDataSourceConfiguration

  •  @EnableJpaRepositories: JPA Repository Bean์„ ํ™œ์„ฑํ™”ํ•ด์ฃผ๋Š” ์–ด๋…ธํ…Œ์ด์…˜
    •  basePackages: SpringBoot๊ฐ€ Bean Scan ๋ฒ”์œ„ ์„ค์ • (Repository ํŒจํ‚ค์ง€ ์„ค์ •)
    •  entityMaganerFactoryRef: DataSource, Hibernate Property, Entity ์„ค์ • (Entity ํŒจํ‚ค์ง€ ์„ค์ •)
    •  transactionManagerRef: ์Šคํ”„๋ง์˜ ํŠธ๋žœ์žญ์…˜ ์„ค์ •
๋ฉ€ํ‹ฐ ๋ฐ์ดํ„ฐ์†Œ์Šค์—์„œ ํŠธ๋žœ์žญ์…˜์„ ๋ฌถ์–ด์ฃผ๋ ค๋ฉด ChainedTransactionManager ๋ผ๋Š” ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์„ค์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
์ฐธ๊ณ : https://taes-k.github.io/2020/06/09/chained-transaction-manager/
  •  @Primary: ์Šคํ”„๋ง์—์„œ ํ•˜๋‚˜์˜ ํƒ€์ž…์— ๋Œ€ํ•ด ์—ฌ๋Ÿฌ ๊ฐœ์˜ Bean์ด ์กด์žฌํ•  ์ˆ˜ ์—†๊ธฐ๋•Œ๋ฌธ์— ์šฐ์„ ์ˆœ์œ„๋ฅผ ์„ค์ •ํ•˜๋Š” ์–ด๋…ธํ…Œ์ด์…˜
  • mainEntityManager(): ์œ„ entityManagerFactoryRef ์†์„ฑ์— ์‚ฌ์šฉํ•  Bean ์ƒ์„ฑ ๋ฉ”์„œ๋“œ
    • LocalContainerEntityManagerFactoryBean: JPA EntityManagerFactory๋ฅผ ์ƒ์„ฑํ•˜๋Š” FactoryBean์œผ๋กœ DataSource, Entity๊ฐ€ ์œ„์น˜ํ•œ ๊ฒฝ๋กœ Scan ์„ค์ •, Hibernate ๊ธฐ๋ฐ˜์œผ๋กœ ๋™์ž‘ํ•˜๋Š” ๊ฒƒ์„ ์„ค์ •ํ•˜๋Š” JpaVenoderAdapter ๋“ฑ์„ ์ง€์ •ํ•ฉ๋‹ˆ๋‹ค.

basePackages
entityMaganerFactoryRef, transactionManagerRef

 

ProductDataSourceConfiguration

@Primary ์–ด๋…ธํ…Œ์ด์…˜์„ ์ œ์™ธํ•˜๋ฉด UserDataSource์™€ ์„ค์ •์€ ๋™์ผํ•ฉ๋‹ˆ๋‹ค.

 

 

๐ŸŽˆ Test

์œ„์™€ ๊ฐ™์ด ๊ฐ„๋‹จํ•œ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ์ž‘์„ฑํ•˜๊ณ  User, Product API๋ฅผ ํ˜ธ์ถœํ•ด๋ณด๋ฉด ๊ฐ๊ฐ ๋‹ค๋ฅธ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ๋ฐ์ดํ„ฐ๊ฐ€ ์ €์žฅ์ด๋ฉ๋‹ˆ๋‹ค.

datasource
datasource-second

 

 

๐Ÿ“„ ์ฐธ๊ณ ๋ฌธ์„œ

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€