Spring Boot使用多数据源

Spring Boot使用多数据源

由于项目中需要使用多个数据库,这里简单说下如何在Spring Boot中配置多个数据源。这里我使用的持久层框架是Mybatis。

配置文件

pom包就不贴了比较简单该依赖的就依赖,主要是数据库这边的配置:

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

一个springboot_database_1库和一个springboot_database_2库,其中springboot_database_1位主库,在使用的过程中必须指定主库,不然会报错。

数据源配置

springboot_database_1数据源配置

package com.lay.mvc.config;


/**
 * @Description:
 * @Author: lay
 * @Date: Created in 11:25 2018/12/14
 * @Modified By:IntelliJ IDEA
 */
@Configuration
@MapperScan(basePackages = "com.lay.mvc.dao.db1", sqlSessionTemplateRef  = "sqlSessionTemplate1")
public class DataSource1Config {

    @Bean(name="dataSource1")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    @Primary
    public DataSource dataSource1(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name="sqlSessionFactory1")
    @Primary
    public SqlSessionFactory sqlSessionFactory1(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        bean.setDataSource(dataSource);
        bean.setTypeAliases(new Class[]{Person.class});
        bean.setTypeHandlersPackage("com.lay.mvc.typehandler");


        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db1/*.xml"));
        return bean.getObject();
    }

    @Bean(name="transactionManager1")
    @Primary
    public DataSourceTransactionManager transactionManager1(@Qualifier("dataSource1") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name="sqlSessionTemplate1")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate1(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

最关键的地方就是这块了,一层一层注入,首先创建DataSource,然后创建SqlSessionFactory再创建事务,最后包装到SqlSessionTemplate中。其中需要指定分库的mapper文件地址,以及分库dao层代码

@MapperScan(basePackages = "com.lay.mvc.dao.db1", sqlSessionTemplateRef  = "sqlSessionTemplate1")

这块的注解就是指明了扫描dao层,并且给dao层注入指定的SqlSessionTemplate。所有@Bean都需要按照命名指定正确。

springboot_database_2数据源配置

package com.lay.mvc.config;


/**
 * @Description:
 * @Author: lay
 * @Date: Created in 11:25 2018/12/14
 * @Modified By:IntelliJ IDEA
 */
@Configuration
@MapperScan(basePackages = "com.lay.mvc.dao.db2", sqlSessionTemplateRef  = "sqlSessionTemplate2")
public class DataSource2Config {

    @Bean(name="dataSource2")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource dataSource2(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name="sqlSessionFactory2")
    public SqlSessionFactory sqlSessionFactory2(@Qualifier("dataSource2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        bean.setConfiguration(configuration);
        bean.setDataSource(dataSource);
        bean.setTypeAliases(new Class[]{Person.class});
        bean.setTypeHandlers(new SexTypeHandler[]{new SexTypeHandler()});
        //bean.setTypeHandlersPackage("com.lay.mvc.typehandler");
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/db2/*.xml"));
        return bean.getObject();
    }

    @Bean(name="transactionManager2")
    public DataSourceTransactionManager transactionManager2(@Qualifier("dataSource2") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name="sqlSessionTemplate2")
    public SqlSessionTemplate sqlSessionTemplate2(@Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

dao层和xml层

dao层和xml需要按照库来分在不同的目录,比如:db1库dao层在com.lay.mvc.dao.db1包下,db2库在com.lay.mvc.dao.db2

Person1Dao

public interface Person1Dao {
	
	List getAll();
	
	UserEntity getOne(Long id);

	void insert(UserEntity user);

	void update(UserEntity user);

	void delete(Long id);

}

Person2Dao

public interface Person2Dao{
	
	List<UserEntity> getAll();
	
	UserEntity getOne(Long id);

	void insert(UserEntity user);

	void update(UserEntity user);

	void delete(Long id);

}

xml层

person1Mapper



<mapper namespace="com.lay.mvc.dao.db1.Person1Dao" >
    <resultMap id="BaseResultMap" type="com.lay.entity.Person" >
        <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>

person2Mapper和person1Mapper类似。

测试

测试可以使用SpringBootTest,也可以放到Controller中,这里只贴Controller层的使用

@RestController
public class UserController {

    @Autowired
    private User1Dao user1Dao;

	@Autowired
	private User2Dao user2Dao;
	
	@RequestMapping("/getUsers")
	public List<UserEntity> getUsers() {
		List<UserEntity> users=user1Dao.getAll();
		return users;
	}
	
    @RequestMapping("/getUser")
    public UserEntity getUser(Long id) {
    	UserEntity user=user2Dao.getOne(id);
        return user;
    }
    
    @RequestMapping("/add")
    public void save(UserEntity user) {
        user2Dao.insert(user);
    }
    
    @RequestMapping(value="update")
    public void update(UserEntity user) {
        user2Dao.update(user);
    }
    
    @RequestMapping(value="/delete/{id}")
    public void delete(@PathVariable("id") Long id) {
        user1Dao.delete(id);
    }
    
}

你可能感兴趣的:(Spring,Boot,数据库)