springboot-mybatis整合多数据源方式之一配置法(亦称分包方式)
环境: intellij idea 2017.1.4 + spring boot 2.0
1 文档结构图:
2 数据库配置相关类
先在application.properties 文件中添加数据库的配置
## 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
注意项: spring.datasource.db1.jdbc-url 数据库地址要这么写,而不是 spring.datasource.url
否则运行时会报如下的错误:“jdbcUrl is required with driverClassName.”
在datasouce目录下增加DataSourceConfig1,DataSourceConfig2文件,如下:
DataSourceConfig1:
package com.neo.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
//表示这个类为一个配置类
@Configuration
// 配置mybatis的接口类放的地方
@MapperScan(basePackages = "com.neo.mapper.db1", sqlSessionFactoryRef = "db1SqlSessionFactory")
public class DataSourceConfig1 {
// 将这个对象放入Spring容器中
@Bean(name = "db1DataSource")
// 表示这个数据源是默认数据源
@Primary
// 读取application.properties中的配置参数映射成为一个对象
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.db1")
public DataSource getDateSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db1SqlSessionFactory")
// 表示这个数据源是默认数据源
@Primary
// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 设置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db1/*.xml"));
return bean.getObject();
}
@Bean("db1SqlSessionTemplate")
// 表示这个数据源是默认数据源
@Primary
public SqlSessionTemplate db1sqlsessiontemplate(
@Qualifier("db1SqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
}
DataSourceConfig2:
package com.neo.datasource;
/**
* Created by xxx on 2019/3/15.
*/
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
//表示这个类为一个配置类
@Configuration
// 配置mybatis的接口类放的地方
@MapperScan(basePackages = "com.neo.mapper.db2", sqlSessionFactoryRef = "db2SqlSessionFactory")
public class DataSourceConfig2 {
// 将这个对象放入Spring容器中
@Bean(name = "db2DataSource")
// 表示这个数据源是默认数据源
// 读取application.properties中的配置参数映射成为一个对象
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.db2")
public DataSource getDateSource2() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db2SqlSessionFactory")
// 表示这个数据源是默认数据源
// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
// 设置mybatis的xml所在位置
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db2/*.xml"));
return bean.getObject();
}
@Bean("db2SqlSessionTemplate")
// 表示这个数据源是默认数据源
@Primary
public SqlSessionTemplate db2sqlsessiontemplate(
@Qualifier("db2SqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
}
实体表操作相关类文件
entity:
package com.neo.entity;
import org.springframework.stereotype.Component;
@Component
public class User {
private Long id;
private String username;
private int age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
package com.neo.entity;
import org.springframework.stereotype.Component;
@Component
public class Sound {
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
private String title;
}
resource/mapper/db1/user.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.db1.UserMapper">
<select id="getUser" resultType="com.neo.entity.User">
select * from user
<where>
<if test="username != null">
username=#{username}
</if>
<if test="age!= null">
and age=#{age}
</if>
</where>
</select>
<delete id="deleteUser" parameterType="Integer">
delete from user where id =#{id}
</delete>
<insert id="addUser" parameterType="com.neo.entity.User">
insert into user(id,username,age)values(#{id},#{username},#{age})
</insert>
<update id="updateUser" parameterType="com.neo.entity.User">
update user
<set>
<if test = "username != null">
user.username = #{username},
</if>
<if test = "age != 0">
user.age = #{age}
</if>
</set>
where id = #{id}
</update>
</mapper>
resource/mapper/db2/sound.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.db2.SoundMapper">
<select id="getSound" resultType="com.neo.entity.Sound">
select * from t_sound
<where>
<if test="title != null">
title=#{title}
</if>
<if test="id!= null">
and id=#{id}
</if>
</where>
</select>
<delete id="deleteSound" parameterType="Integer">
delete from t_sound where id =#{id}
</delete>
<insert id="addSound" parameterType="com.neo.entity.Sound">
insert into t_sound(id,title)values(#{id},#{title})
</insert>
<update id="updateSound" parameterType="com.neo.entity.Sound">
update t_sound
<set>
<if test = "title != null">
sound.title = #{title},
</if>
</set>
where id = #{id}
</update>
</mapper>
mapper/db1/UserMapper
package com.neo.mapper.db1;
import com.neo.entity.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
//获取用户名单
public List<User> getUser() throws Exception;
//根据id删除用户
public void deleteUser(int id)throws Exception;
//新增用户
public void addUser(User user)throws Exception;
//修改用户信息
public void updateUser(User user) throws Exception;
// //用注解实现的
// //获取用户名单
// @Select("select * from user")
// public List<User> getUser() throws Exception;
// //根据id删除用户
// @Delete("delete from user where id = #{id}")
// public void deleteUser(int id)throws Exception;
// //新增用户
// @Insert("insert into user(id,username,age)values(#{id},#{username},#{age})")
// public void addUser(User user)throws Exception;
// //修改用户信息
// @Update("update user set username = #{name} where id = #{id}")
// public void updateUser(User user) throws Exception;
}
mapper/db2/SoundMapper
package com.neo.mapper.db2;
import com.neo.entity.Sound;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface SoundMapper {
//获取列表
public List<Sound> getSound() throws Exception;
//根据id删除
public void deleteSound(int id)throws Exception;
//新增
public void addSound(Sound sound)throws Exception;
//修改信息
//public void updateSound(Sound sound) throws Exception;
}
service 这里没有分文件夹,也可以分
UserService:
package com.neo.service;
import com.neo.entity.User;
import java.util.List;
public interface UserService {
//显示所有用户
public List<User> getUser()throws Exception;
//根据id删除用户
public void deleteUser(int id)throws Exception;
//新增用户
public void addUser(User user)throws Exception;
}
package com.neo.service;
import com.neo.entity.User;
import com.neo.mapper.db1.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getUser() throws Exception {
return userMapper.getUser();
}
//根据id删除用户
@Override
public void deleteUser(int id) throws Exception {
userMapper.deleteUser(id);
}
//新增用户
@Override
public void addUser(User user) throws Exception {
userMapper.addUser(user);
}
}
SoundService:
package com.neo.service;
import com.neo.entity.Sound;
import com.neo.entity.User;
import java.util.List;
public interface SoundService {
//显示所有用户
public List<Sound> getSound()throws Exception;
//根据id删除用户
public void deleteSound(int id)throws Exception;
//新增用户
public void addSound(Sound sound)throws Exception;
}
package com.neo.service;
import com.neo.entity.Sound;
import com.neo.mapper.db2.SoundMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SoundServiceImpl implements SoundService {
@Autowired
private SoundMapper soundMapper;
@Override
public List<Sound> getSound() throws Exception {
return soundMapper.getSound();
}
//根据id删除用户
@Override
public void deleteSound(int id) throws Exception {
soundMapper.deleteSound(id);
}
//新增用户
@Override
public void addSound(Sound sound) throws Exception {
soundMapper.addSound(sound);
}
}
controller
UserController:
package com.neo.controller;
import com.neo.entity.User;
import com.neo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserService userService;
@Autowired
private User user;
//显示用户
@RequestMapping("list")
public List<User> index() throws Exception {
return userService.getUser();
}
//删除用户
@RequestMapping("delete/{id}")
public String delete(@PathVariable int id) throws Exception {
userService.deleteUser(id);
return "你已经删掉了id为"+id+"的用户";
}
//增加用户
@RequestMapping("addUser")
public String addUser() throws Exception {
user.setAge(33);
user.setUsername("阿花");
userService.addUser(user);
return "增加用户";
}
}
SoundController:
package com.neo.controller;
import com.neo.entity.Sound;
import com.neo.service.SoundService;
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 SoundController {
@Autowired
private SoundService soundService;
@Autowired
private Sound sound;
//显示用户
@RequestMapping("sound/list")
public List<Sound> index() throws Exception {
return soundService.getSound();
}
//增加用户
@RequestMapping("sound/add")
public String addSound() throws Exception {
sound.setTitle("平凡之路");
soundService.addSound(sound);
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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
至些所有的文件都ok了,编译运行
http://localhost:8080/sound/list
都正常显示,如果数据库表里没有数据,可以用add方法先添加。
附完整测试项目包地址: https://download.****.net/download/huwei2003/11074738
--- end ---