How to specify schema in application.yml with Spring Boot + MyBatis
I wanted to set the database schema in application.yml for Spring Boot + MyBatis, but I could not find much information.
You can do so by doing the following.
The key “dbschema” is used, but you can use any key you like.
mybatis: configuration-properties: dbschema: schemaname
On the Mapper side, if ${dbschema} is used, it can be used out of the blue.
@Select(value="select * from ${dbschema}.Employees ") public Employees findByEmployee();
Specify schema in @Configuration
If you are creating a class with @Configuration, you need to set an instance of the Properties class for the instance of SqlSessionFactoryBean. class, the schema name will be set in the SQL statement.
// These three lines are needed Properties props = new Properties(); props.setProperty("dbschema", "schemaname"); sqlSessionFactory.setConfigurationProperties(props);
サンプル
package jp.co.confrage; import java.util.Properties; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; 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; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.PlatformTransactionManager; @Configuration @MapperScan( basePackages = "com.example.demo.repository.primary", sqlSessionFactoryRef = "sqlSessionFactory1") public class PrimaryConfiguration { @Bean @Primary @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSourceProperties primaryProperties() { return new DataSourceProperties(); } @Bean(name = {"datasource1"}) @Primary public DataSource primaryDataSource( @Qualifier("primaryProperties") DataSourceProperties properties) { return properties.initializeDataSourceBuilder().build(); } @Bean @Primary public PlatformTransactionManager primaryEntityManager(DataSource dataSource1) { return new DataSourceTransactionManager(dataSource1); } @Bean(name = {"sqlSessionFactory1"}) @Primary public SqlSessionFactory sqlSessionFactory(@Qualifier("datasource1") DataSource datasource1) throws Exception { final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean(); sqlSessionFactory.setDataSource(datasource1); final Properties props = new Properties(); props.setProperty("dbschema", "schemaname"); // Specify the schema name here sqlSessionFactory.setConfigurationProperties(props); return sqlSessionFactory.getObject(); } }
コメント