다중 데이터베이스 연결은 하나의 애플리케이션이 두 개 이상의 데이터베이스와 상호작용해야 할 때 사용됩니다. 주로 데이터 이동(백업/복제), 다중 시스템 연동, 또는 분산 데이터베이스 시스템에서 활용됩니다.
DataSource 빈을 다중으로 정의하고 관리합니다.JdbcTemplate 또는 EntityManager를 생성하여 특정 데이터베이스와 작업을 수행합니다.application.properties# 데이터 소스 1 (sample)
spring.datasource1.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource1.jdbc-url=jdbc:mariadb://localhost:3306/sample
spring.datasource1.username=root
spring.datasource1.password=exxyeon
# 데이터 소스 2 (project)
spring.datasource2.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource2.jdbc-url=jdbc:mariadb://localhost:3306/project
spring.datasource2.username=root
spring.datasource2.password=exxyeon
@Bean 설정@SpringBootApplication
public class Jjdbc03Application {
@Bean
@ConfigurationProperties("spring.datasource1")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource2")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}
public static void main(String[] args) {
SpringApplication.run(Jjdbc03Application.class, args);
}
}
DataSource 빈 두 개(dataSource1, dataSource2)를 생성.sample과 project 데이터베이스와 연결.JdbcTemplate 생성JdbcTemplate 생성.-- 복제 대상 데이터베이스로 이동
USE project;
-- source 테이블(dept)의 구조만 복사
CREATE TABLE dept AS SELECT * FROM sample.dept WHERE 1 != 1;
-- 복사된 테이블의 구조 확인
DESC dept;
-- 복사된 데이터 없는지 확인
SELECT COUNT(*) FROM dept;
@Getter
@Setter
public class DeptTO {
private String deptNo;
private String dname;
private String loc;
}
.update())@Override
public void run(String... args) throws Exception {
// 데이터 소스 출력
System.out.println("dataSource1: " + dataSource1().getConnection());
System.out.println("dataSource2: " + dataSource2().getConnection());
// 데이터베이스별 JdbcTemplate 생성
JdbcTemplate jdbcTemplate1 = new JdbcTemplate(dataSource1());
JdbcTemplate jdbcTemplate2 = new JdbcTemplate(dataSource2());
// 원본 데이터 조회 쿼리
String selectSql = "SELECT * FROM dept";
// 복사 대상 테이블에 삽입할 쿼리
String insertSql = "INSERT INTO dept VALUES (?, ?, ?)";
// 데이터베이스 1에서 데이터 조회
List<DeptTO> results = jdbcTemplate1.query(
selectSql,
new BeanPropertyRowMapper<>(DeptTO.class)
);
// 데이터베이스 2로 데이터 복사
for (DeptTO to : results) {
System.out.println(to.getDeptNo());
jdbcTemplate2.update(insertSql, to.getDeptNo(), to.getDname(), to.getLoc());
}
System.out.println("백업 완료");
}
// 테이블 존재 여부 확인
String tableCheckSql = "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?";
Integer count = jdbcTemplate2.queryForObject(
tableCheckSql, Integer.class, "project", "dept");
if (count == 0) {
System.out.println("테이블이 존재하지 않습니다.");
return;
}
@Autowired
private PlatformTransactionManager transactionManager;
@Override
public void run(String... args) throws Exception {
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
try {
// 데이터 이동 로직 실행
for (DeptTO to : results) {
jdbcTemplate2.update(insertSql, to.getDeptNo(), to.getDname(), to.getLoc());
}
transactionManager.commit(status);
System.out.println("백업 완료");
} catch (Exception e) {
transactionManager.rollback(status);
e.printStackTrace();
}
}
다중 데이터베이스 연결
DataSource와 JdbcTemplate를 활용하여 두 개 이상의 데이터베이스와 독립적으로 작업 가능.application.properties 및 @Bean).데이터 복제
확장성
사용 사례