本例将采用maven管理,代码托管在github上,地址:https://github.com/wolf909867753/springboot。
1。创建maven-module,mybatis-mutil-datasource,并在pom.xml中添加springboot依赖
<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/maven-v4_0_0.xsd"> <parent> <artifactId>spring-boot-starter-parentartifactId> <groupId>org.springframework.bootgroupId> <version>1.5.1.RELEASEversion> parent> <modelVersion>4.0.0modelVersion> <artifactId>mybatis-mutil-datasourceartifactId> <packaging>warpackaging> <name>Spring Boot整合Mybatis实现Druid多数据源name> <url>http://maven.apache.orgurl> <properties> <mybatis-spring-boot>1.2.0mybatis-spring-boot> <mysql-spring-boot>5.1.32mysql-spring-boot> <druid>1.0.18druid> properties> <dependencies> <dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-webartifactId> dependency> <dependency> <groupId>org.mybatis.spring.bootgroupId> <artifactId>mybatis-spring-boot-starterartifactId> <version>${mybatis-spring-boot}version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>${mysql-spring-boot}version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>${druid}version> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.12version> <scope>testscope> dependency> dependencies> <build> <finalName>mybatis-mutil-datasourcefinalName> build> project> 1.项目结构介绍 com.springboot.dataSourceConfig – 配置层,这里是数据源的配置,包括 master 和 cluster 的数据源配置
/** * @Primary 标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。「多数据源配置的时候注意,必须要有一个主数据源,用 @Primary 标志该 Bean」 * @MapperScan 扫描 Mapper 接口并容器管理,包路径精确到 master,为了和下面 cluster 数据源做到精确区分 * @Value 获取全局配置文件 application.properties 的 kv 配置,并自动装配 * sqlSessionFactoryRef 表示定义了 key ,表示一个唯一 SqlSessionFactory 实例 * Created by wanglu-jf on 17/6/28. */ @Configuration @MapperScan(basePackages = ClusterConfig.PACKAGE,sqlSessionFactoryRef = "clusterSqlSessionFactory") public class ClusterConfig { public static final String PACKAGE = "com.springboot.dao.cluster"; public static final String MAPPER_LOCATION = "classpath:mapper/cluster/*.xml"; // cluster.datasource.driver-class-name = com.mysql.jdbc.Driver // cluster.datasource.url = jdbc:mysql://localhost:3306/springbootdb_cluster?useUnicode=true&characterEncoding=utf8 // cluster.datasource.username = root // cluster.datasource.password = root @Value("${cluster.datasource.driver-class-name}") private String driverClassName; @Value("${cluster.datasource.url}") private String url; @Value("${cluster.datasource.username}") private String username; @Value("${cluster.datasource.password}") private String password; //初始化数据库连接 @Bean(name="clusterDataSource") public DataSource clusterDataSource(){ DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } //数据源事务管理器 @Bean(name="clusterDataSourceTransactionManager") public DataSourceTransactionManager clusterDataSourceTransactionManager(){ DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(clusterDataSource()); return dataSourceTransactionManager; } //创建Session @Bean(name="clusterSqlSessionFactory") public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource) throws Exception{ final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(clusterDataSource); Resource[] resource = new PathMatchingResourcePatternResolver().getResources(ClusterConfig.MAPPER_LOCATION); sqlSessionFactoryBean.setMapperLocations(resource); return sqlSessionFactoryBean.getObject(); } }
@Configuration // 扫描 Mapper 接口并容器管理 @MapperScan(basePackages = MasterConfig.PACKAGE,sqlSessionFactoryRef = "masterSqlSessionFactory") public class MasterConfig { //master dao 所在的包 public static final String PACKAGE = "com.springboot.dao.master"; //mapper所在目录 private static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml"; // master.datasource.driver-class-name = com.mysql.jdbc.Driver // master.datasource.url = jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8 // master.datasource.username = root // master.datasource.password = root @Value("${master.datasource.driver-class-name}") private String driverClassName; @Value("${master.datasource.url}") private String url; @Value("${master.datasource.username}") private String username; @Value("${master.datasource.password}") private String password; //初始化数据库连接 @Bean(name="masterDataSource") @Primary public DataSource masterDataSource(){ DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } //数据源事务管理器 @Bean(name="masterDataSourceTransactionManager") @Primary public DataSourceTransactionManager masterDataSourceTransactionManager(){ return new DataSourceTransactionManager(masterDataSource()); } //创建Session @Bean(name="masterSqlSessionFactory") @Primary public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception{ final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(masterDataSource); //MapperLocations(Resource[] mapperLocations) Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources(MasterConfig.MAPPER_LOCATION); sqlSessionFactoryBean.setMapperLocations(mapperLocations); return sqlSessionFactoryBean.getObject(); } }
@RestController @RequestMapping("user/") public class UserController { @Autowired private IUserService userService; @RequestMapping(value="query/{id}",method = RequestMethod.GET) public User queryById(@PathVariable("id") int id){ User user = this.userService.queryById(id); return user; } }
@Mapper public interface IUserDao { /** * 根据用户id获取用户信息 * * @param userId * @return */ public User queryByUserId(@Param("userId") int userId); }
@Mapper public interface ICityDao { /** * 根据城市名称,查询城市信息 * * @param cityId 城市名 */ public City queryById(@Param("cityId") int cityId); }
public class City implements Serializable{ /** * 城市编号 */ private Long id; /** * 省份编号 */ private Long provinceId; /** * 城市名称 */ private String cityName; /** * 描述 */ private String description;getter/setter....
public class User { /** * 城市编号 */ private Long id; /** * 城市名称 */ private String userName; /** * 描述 */ private String description;
getter/setter.... }
public interface IUserService { /** * 根据用户id获取用户信息,包括从库的地址信息 * @param userId * @return */ public User queryById(int userId); }
@Service public class UserServiceImpl implements IUserService { @Autowired private IUserDao userDao; // user数据源 @Autowired private ICityDao cityDao; //city数据源 /** * 根据用户id获取用户信息,包括从库的地址信息 * @param id * @return */ @Override public User queryById(int id) { User user = this.userDao.queryByUserId(id); City city = this.cityDao.queryById(id); if(null != user && null != city){ user.setCity(city); } return user; } }
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
## master 数据源配置 master.datasource.driver-class-name = com.mysql.jdbc.Driver master.datasource.url = jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8 master.datasource.username = root master.datasource.password = root ## cluster 数据源配置 cluster.datasource.driver-class-name = com.mysql.jdbc.Driver cluster.datasource.url = jdbc:mysql://localhost:3306/springbootdb_cluster?useUnicode=true&characterEncoding=utf8 cluster.datasource.username = root cluster.datasource.password = root
xml version="1.0" encoding="UTF-8" ?> mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.springboot.dao.cluster.IUserDao"> <resultMap id="BaseResultMap" type="com.springboot.domain.User"> <result column="id" property="id" /> <result column="user_name" property="userName" /> <result column="description" property="description" /> resultMap> <parameterMap id="user" type="com.springboot.domain.User"/> <sql id="Base_Column_List"> id, user_name, description sql> <select id="queryByUserId" resultMap="BaseResultMap" parameterType="int"> select <include refid="Base_Column_List" /> from user where id = #{userId} select> mapper>
xml version="1.0" encoding="UTF-8" ?> mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.springboot.dao.master.ICityDao"> <resultMap id="BaseResultMap" type="com.springboot.domain.City"> <result column="id" property="id" /> <result column="province_id" property="provinceId" /> <result column="city_name" property="cityName" /> <result column="description" property="description" /> resultMap> <parameterMap id="City" type="com.springboot.domain.City"/> <sql id="Base_Column_List"> id, province_id, city_name, description sql> <select id="queryById" resultMap="BaseResultMap" parameterType="int"> select <include refid="Base_Column_List" /> from city where id = #{cityId} select> mapper>