How to specify schema in application.yml with Spring Boot + MyBatis

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.

    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");



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.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;

  basePackages = "com.example.demo.repository.primary",
  sqlSessionFactoryRef = "sqlSessionFactory1")
public class PrimaryConfiguration {
  @ConfigurationProperties(prefix = "spring.datasource.primary")
  public DataSourceProperties primaryProperties() {
    return new DataSourceProperties();

  @Bean(name = {"datasource1"})
  public DataSource primaryDataSource(
    @Qualifier("primaryProperties") DataSourceProperties properties) {
  return properties.initializeDataSourceBuilder().build();

  public PlatformTransactionManager primaryEntityManager(DataSource dataSource1) {
    return new DataSourceTransactionManager(dataSource1);

  @Bean(name = {"sqlSessionFactory1"})
  public SqlSessionFactory sqlSessionFactory(@Qualifier("datasource1") DataSource datasource1)
      throws Exception {
    final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
    final Properties props = new Properties();
    props.setProperty("dbschema", "schemaname"); // Specify the schema name here
    return sqlSessionFactory.getObject();