springboot-mybatis整合多数据源之sqlserver

环境: intellij idea 2017.1.4 + spring boot 2.0

代码文档结构图:

注:此代码中的db1,db2为mysql数据源相关,db3为sqlserver数据源

2 数据库配置相关类

先在application.properties 文件中添加数据库的配置

#spring.datasource.driverClassName=com.mysql.jdbc.Driver
#spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
#spring.datasource.username=root
#spring.datasource.password=
#mybatis.mapper-locations: classpath:mapper/*.xml


## db1 database
spring.datasource.db1.jdbc-url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.db1.username=root
spring.datasource.db1.password=
spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver
## db2 database
spring.datasource.db2.jdbc-url=jdbc:mysql://localhost:3306/news?useUnicode=true&characterEncoding=UTF-8
spring.datasource.db2.username=root
spring.datasource.db2.password=
spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
## db3 database
spring.datasource.db3.jdbc-url=jdbc:sqlserver://ip:port;DatabaseName=dbname
spring.datasource.db3.username=dbaccountname
spring.datasource.db3.password=dbaccountpassowrd
spring.datasource.db3.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

## Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=127.0.0.1  
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=200  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1  
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10 
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)
spring.redis.timeout=3000 

在datasouce目录下增加DataSourceConfig3文件,DataSourceConfig1,DataSourceConfig2略(资源代码里有),如下:

package com.neo.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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.neo.mapper.db3", sqlSessionFactoryRef = "db3SqlSessionTemplate")
public class DataSourceConfig3 {

    @Bean(name = "sqlServerDataSource")
    @Qualifier("sqlServerDataSource")
    @ConfigurationProperties(prefix="spring.datasource.db3")
    public DataSource getMyDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(
            @Qualifier("sqlServerDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    private static final String MAPPER_PATH = "classpath:mapper/db3/*.xml";

    private static final String ENTITY_PACKAGE = "com.neo.mapper.db3";
    @Bean(name = "db3SqlSessionTemplate")
    public SqlSessionFactory devSqlSessionFactory(
            @Qualifier("sqlServerDataSource") DataSource ddataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(ddataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources(MAPPER_PATH));
        sessionFactory.setTypeAliasesPackage(ENTITY_PACKAGE);
        return sessionFactory.getObject();
    }

    @Bean
    public PlatformTransactionManager sqlServerTransactionManager(@Qualifier("sqlServerDataSource") DataSource sqlServerDataSource)
    {
        return new DataSourceTransactionManager(sqlServerDataSource);
    }

}

实体表操作相关类文件

entity

package com.neo.entity.db3;

import org.springframework.stereotype.Component;


@Component
public class City {
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public int getParentId() {
        return ParentId;
    }

    public void setParentId(int parentId) {
        ParentId = parentId;
    }

    public int getSort() {
        return Sort;
    }

    public void setSort(int sort) {
        Sort = sort;
    }

    private String Name;
    private int ParentId;
    private  int Sort;


}

resource/mapper/db3/city.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.neo.mapper.db3.CityMapper">
    <select id="getCity" resultType="com.neo.entity.db3.City">
        select * from T_City
        <where>
            <if test="name != null">
                Name=#{name}
            </if>

            <if test="id!= null">
                and id=#{id}
            </if>
        </where>
    </select>
    <delete id="deleteCity" parameterType="Integer">
        delete from T_City where id =#{id}
    </delete>
    <insert id="addCity" parameterType="com.neo.entity.db3.City">
    insert into T_City(Name,ParentId,Sort)values(#{Name},#{ParentId},#{Sort})
</insert>
    <update id="updateCity" parameterType="com.neo.entity.db3.City">
        update T_City
        <set>
            <if test = "name != null">
                city.name = #{name},
            </if>
        </set>
        where id = #{id}
    </update>
</mapper>

mapper/db3/CityMapper

package com.neo.mapper.db3;

import com.neo.entity.db3.City;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;


@Mapper
public interface CityMapper {
    //获取列表
    public List<City> getCity() throws Exception;
    //根据id删除
    public void deleteCity(int id)throws Exception;
    //新增
    public void addCity(City city)throws Exception;

    //修改信息
    //public void updateCity(City city) throws Exception;

}

CityService:

package com.neo.service;

import com.neo.entity.db3.City;

import java.util.List;


public interface CityService {
    //显示所有用户
    public List<City> getCity()throws Exception;
    //根据id删除用户
    public void deleteCity(int id)throws Exception;
    //新增用户
    public void addCity(City city)throws Exception;
}
package com.neo.service;

import com.neo.entity.db3.City;
import com.neo.mapper.db3.CityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class CityServiceImpl implements CityService {

    @Autowired
    private CityMapper cityMapper;
    @Override
    public List<City> getCity() throws Exception {
        return cityMapper.getCity();
    }
    //根据id删除用户
    @Override
    public void deleteCity(int id) throws Exception {
        cityMapper.deleteCity(id);
    }
    //新增用户
    @Override
    public void addCity(City city) throws Exception {
        cityMapper.addCity(city);
    }
}

controller

package com.neo.controller;

import com.neo.entity.db3.City;
import com.neo.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
public class CityController {

    @Autowired
    private CityService cityService;
    @Autowired
    private City city;
    //显示用户
    @RequestMapping("city/list")
    public List<City> index() throws Exception {
        return cityService.getCity();
    }

    //增加用户
    @RequestMapping("city/add")
    public String addCity() throws Exception {
        city.setName("test省份");
        city.setParentId(0);
        city.setSort(0);
        cityService.addCity(city);
        return "增加";
    }
}

pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.neo</groupId>
	<artifactId>spring-boot-hello</artifactId>
	<version>1.0</version>
	<packaging>jar</packaging>

	<name>spring-boot-hello</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
	     <dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-starter-web</artifactId>
	    </dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>com.microsoft.sqlserver</groupId>
			<artifactId>mssql-jdbc</artifactId>
			<version>6.4.0.jre8</version>
			<scope>runtime</scope>
		</dependency>
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
	

</project>

至些所有的文件都ok了,编译运行 

http://localhost:8080/city/list

http://localhost:8080/list

都正常显示,如果数据库表里没有数据,可以用add方法先添加。

附完整测试项目包地址: https://download.csdn.net/download/huwei2003/11131140

--- end ---
 

猜你喜欢

转载自blog.csdn.net/huwei2003/article/details/89419086