springboot多數據源配置

提及多數據源,通常都來解決那些問題呢,主從模式或者業務比較複雜須要鏈接不一樣的分庫來支持業務。咱們項目是後者的模式,網上找了不少,大都是根據jpa來作多數據源解決方案,要不就是老的spring多數據源解決方案,還有的是利用aop動態切換,感受有點小複雜,其實我只是想找一個簡單的多數據支持而已,折騰了兩個小時整理出來,供你們參考。html

廢話很少說直接上代碼吧java

配置文件

pom包就不貼了比較簡單該依賴的就依賴,主要是數據庫這邊的配置:mysql

mybatis.config-locations=classpath:mybatis/mybatis-config.xml

spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver
spring.datasource.test1.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.test1.username = root
spring.datasource.test1.password = root

spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver
spring.datasource.test2.url = jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8
spring.datasource.test2.username = root
spring.datasource.test2.password = root

一個test1庫和一個test2庫,其中test1位主庫,在使用的過程當中必須制定主庫,否則會報錯。
數據源配置spring

@Configuration@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")
public class DataSource1Config {    

    @Bean(name = "test1DataSource")   
    @ConfigurationProperties(prefix = "spring.datasource.test1")    @Primary
    public DataSource testDataSource() {
            return DataSourceBuilder.create().build();
    }
            
    @Bean(name = "test1SqlSessionFactory")    
    @Primary
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));        
        return bean.getObject();
    }    
    
    @Bean(name = "test1TransactionManager")    
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {        
        return new DataSourceTransactionManager(dataSource);
    }    
    
    @Bean(name = "test1SqlSessionTemplate")    
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {        
          return new SqlSessionTemplate(sqlSessionFactory);
     }

}

最關鍵的地方就是這塊了,一層一層注入,先建立DataSource,在建立SqlSessionFactory在建立事務,最後包裝到SqlSessionTemplate中。其中須要制定分庫的mapper文件地址,以及分庫到層代碼sql

@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")

這塊的註解就是指明瞭掃描dao層,而且給dao層注入指定的SqlSessionTemplate。全部@Bean都須要按照命名指定正確。
dao層和xml層
dao層和xml須要按照庫來分在不一樣的目錄,好比:test1庫dao層在com.neo.mapper.test1包下,test2庫在com.neo.mapper.test1數據庫

public interface User1Mapper {   
    List<UserEntity> getAll();    
    UserEntity getOne(Long id);
    void insert(UserEntity user);
    void update(UserEntity user);    
    void delete(Long id);
}

xml層mybatis

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.neo.mapper.test1.User1Mapper" >
    <resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" >
        <id column="id" property="id" jdbcType="BIGINT" />
        <result column="userName" property="userName" jdbcType="VARCHAR" />
        <result column="passWord" property="passWord" jdbcType="VARCHAR" />
        <result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/>
        <result column="nick_name" property="nickName" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="Base_Column_List" >
        id, userName, passWord, user_sex, nick_name    
    </sql>

    <select id="getAll" resultMap="BaseResultMap"  >
       SELECT 
       <include refid="Base_Column_List" />
       FROM users    
    </select>

    <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
        SELECT 
       <include refid="Base_Column_List" />
       FROM users
       WHERE id = #{id}    
    </select>

    <insert id="insert" parameterType="com.neo.entity.UserEntity" >
       INSERT INTO 
            users
            (userName,passWord,user_sex) 
        VALUES
            (#{userName}, #{passWord}, #{userSex})    
    </insert>

    <update id="update" parameterType="com.neo.entity.UserEntity" >
       UPDATE 
            users 
       SET 
        <if test="userName != null">userName = #{userName},</if>
        <if test="passWord != null">passWord = #{passWord},</if>
        nick_name = #{nickName}
       WHERE 
            id = #{id}    
     </update>

    <delete id="delete" parameterType="java.lang.Long" >
       DELETE FROM
             users 
       WHERE 
             id =#{id}    
   </delete>
   
</mapper>

測試
測試可使用SpringBootTest,也能夠放到Controller中,這裏只貼Controller層的使用app

@RestControllerpublic class UserController {    
    @Autowired
    private User1Mapper user1Mapper;    
    
    @Autowired
    private User2Mapper user2Mapper;    
    
    @RequestMapping("/getUsers")    
    public List<UserEntity> getUsers() {
        List<UserEntity> users=user1Mapper.getAll();
        return users;
    }    
    
    @RequestMapping("/getUser")    
    public UserEntity getUser(Long id) {
        UserEntity user=user2Mapper.getOne(id);        
        return user;
    }    
    
    @RequestMapping("/add")    
    public void save(UserEntity user) {
        user2Mapper.insert(user);
    }    
    
    @RequestMapping(value="update")    
    public void update(UserEntity user) {
        user2Mapper.update(user);
    }    
    
    @RequestMapping(value="/delete/{id}")    
    public void delete(@PathVariable("id") Long id) {
        user1Mapper.delete(id);
    }

}



做者:小紅牛
連接:https://www.jianshu.com/p/f7986fff887d
來源:簡書
簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。測試

相關文章
相關標籤/搜索