0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MyBatisで複数のDBに接続する

Last updated at Posted at 2024-08-26

DB接続設定ファイル(yml)

今回は以下の設定を行う

  • application.ymlにdatasource2を追加する

  • 一方はSQL Server、もう一方はOracle DBに接続する

application.yml
  datasource:
    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
    url: jdbc:sqlserver://localhost:1433;databaseName=maindb
    username: hoge
    password: hogehoge
  datasource2:
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@//localhost:1521/oracledb
    username: hoge2
    password: hogehoge2 

Spring Configuration

  • 主に接続する方のDBのconfigには以下のように実装し、primaryを付ける
@Configuration
@MapperScan(basePackages = { "jp.co.sample.main.mapper", "jp.co.sample.main.repository" },
sqlSessionFactoryRef = "sqlSessionFactory")
public class DataSourceConfig {
	@Bean(name = { "datasourceProperties" })
	@Primary
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSourceProperties datasourceProperties() {
		return new DataSourceProperties();
	}

	@Bean(name = { "datasource" })
	@Primary
	public DataSource datasource(@Qualifier("datasourceProperties") DataSourceProperties properties) {
		return properties.initializeDataSourceBuilder().build();
	}

	@Bean(name = { "txManager" })
	@Primary
	public PlatformTransactionManager txManager(@Qualifier("datasource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = { "sqlSessionFactory" })
	@Primary
	public SqlSessionFactory sqlSessionFactory(@Qualifier("datasource") DataSource datasource) throws Exception {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(datasource);
		return (SqlSessionFactory) sqlSessionFactory.getObject();
	}
} 
  • 同じように別DB用のconfigを用意する
@Configuration
@MapperScan(basePackages = { "jp.co.sample.sub.mapper", "jp.co.sample.sub.repository" },
sqlSessionFactoryRef = "sqlSessionFactory2")
public class DataSource2Config {
	@Bean(name = { "datasource2Properties" })
	@ConfigurationProperties(prefix = "spring.datasource2")
	public DataSourceProperties datasourceProperties() {
		return new DataSourceProperties();
	}

	@Bean(name = { "datasource2" })
	public DataSource datasource(@Qualifier("datasource2Properties") DataSourceProperties properties) {
		return properties.initializeDataSourceBuilder().build();
	}

	@Bean(name = { "txManager2" })
	public PlatformTransactionManager txManager(@Qualifier("datasource2") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = { "sqlSessionFactory2" })
	public SqlSessionFactory sqlSessionFactory(@Qualifier("datasource2") DataSource datasource) throws Exception {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(datasource);
		return (SqlSessionFactory) sqlSessionFactory.getObject();
	}
} 

MyBatis Generatorの設定

  • DB毎に別のパッケージを指定することで複数DB接続を可能にする
MyBatis Generator Configuration

<generatorConfiguration>
    <properties resource="mybatis/mygenerator.properties" />
    <context id="schema1" targetRuntime="MyBatis3">

        <jdbcConnection driverClass="${db.driverClassName1}" connectionURL="${db.url1}" userId="${db.username1}" password="${db.password1}">
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

        <javaModelGenerator targetPackage="${package.model1}" targetProject="test">
            <property name="trimStrings" value="true"></property>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="${package.mapper1}" targetProject="test/src/main/resources">
        </sqlMapGenerator>

        <javaClientGenerator targetPackage="${package.mapper1}" targetProject="test" type="XMLMAPPER">
        </javaClientGenerator>

    </context>

    <context id="schema2" targetRuntime="MyBatis3">

        <jdbcConnection driverClass="${db.driverClassName2}" connectionURL="${db.url2}" userId="${db.username2}" password="${db.password2}">
            <property name="nullCatalogMeansCurrent" value="true" />
        </jdbcConnection>

        <javaModelGenerator targetPackage="${package.model2}" targetProject="test">
            <property name="trimStrings" value="true"></property>
        </javaModelGenerator>

        <sqlMapGenerator targetPackage="${package.mapper2}" targetProject="test/src/main/resources">
        </sqlMapGenerator>

        <javaClientGenerator targetPackage="${package.mapper2}" targetProject="test" type="XMLMAPPER">
        </javaClientGenerator>

    </context>
</generatorConfiguration>


mygenerator.properties
db.driverClassName1=com.microsoft.sqlserver.jdbc.SQLServerDriver
db.url1=jdbc:sqlserver://localhost:1433;databaseName=maindb
db.username1=hoge
db.password1=hogehoge
package.model1=jp.co.sample.main.model
package.mapper1=jp.co.sample.main.mapper

db.driverClassName2=oracle.jdbc.driver.OracleDriver
db.url2=jdbc:oracle:thin:@//localhost:1521/oracledb
db.username2=hoge2
db.password2=hogehoge2
package.model2=jp.co.sample.sub.model
package.mapper2=jp.co.sample.sub.mapper

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?