Mybatis多环境数据源配置方式之environment标签

在部署项目的时候每次修改相关配置文件都比较麻烦,虽然项目基本信息配置已经可以由环境的不同而动态读取,但Mybatis一直不能,每次打war包的时候都需要修改相关密码。目前可以使用Mybatis的environment标签根据环境动态引入指定的dataSource,这样项目部署能更方便。
实现步聚如下:

修改Mybatis配置文件

  <environments default="development">
    
    <environment id="development">
      <transactionManager type="JDBC">
          <property name="" value=""/>
      transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/rfunbook?useUnicode=true&characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
     dataSource>
    environment>

    
    <environment id="product">
      <transactionManager type="JDBC">
          <property name="" value=""/>
      transactionManager>
      <dataSource type="UNPOOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/rfunbook?useUnicode=true&characterEncoding=UTF-8"/>
         <property name="username" value="root"/>
        <property name="111111" value="rfunbook@admin"/>
     dataSource>
    environment>
  environments>

修改创建SqlSessionFactory方法

public class DBMybatisUtil {

    private final static SqlSessionFactory sqlSessionFactory;  

    private static String resourcePath = "com/common/config/Configuration.xml";

    static{  
        Reader reader = null;  
        try {  
            reader = Resources.getResourceAsReader(DBMybatisUtil.resourcePath);  
        } catch (IOException e) {  
            System.out.println(e.getMessage());  
        }  
        String environment = Common.getDevelopmentEnvironment();
        environment = environment.equals("dev") || environment.equals("") ? "development" : environment;
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader, environment);  
    }  

    public static SqlSessionFactory getSqlsessionfactory() {  
        return sqlSessionFactory;  
    } 
}

你可能感兴趣的:(Mybaitis)