springboot初学---mybatis多数据源的解决方案
1.使用xml方式
<1>.application.properties配置文件
## mybatis使用xml的方式连接数据库
# mybatis.config-location=classpath:mybatis/mybatis-config.xml
# mybatis多数据原的配置
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 =
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 =
说明:test1和test2位两个数据库,在使用过程中必须指明一个位主库,否则报错
<2>.数据源配置
package com.example.demo.datasource; import javax.sql.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.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; 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 org.springframework.jdbc.datasource.DataSourceTransactionManager; @Configuration
/**
* 指明了扫描dao层,并且给dao层注入指定的SqlSessionTemplate
*/
@MapperScan(basePackages = "com.example.demo.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);
}
}
数据源test2和test1一样,只需要将@Primary注解去掉
<3>.mybatis-config.xml配置文件(配置头信息外空壳子就可以)
<4>.DAO层编写
public interface User1Mapper {
List<UserEntity> getAll();
UserEntity getOne(Integer id);
void insert(UserEntity user);
void update(UserEntity user);
void delete(Integer id);
}
User2Mapper.java和这个一样即可
<5>.User1Mapper.xml文件配置
<?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.example.demo.mapper.test1.User1Mapper" >
<resultMap id="BaseResultMap" type="com.example.demo.domain.UserEntity" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="passWord" property="passWord" jdbcType="VARCHAR" />
<result column="user_sex" property="userSex" jdbcType="VARCHAR"/>
<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.Integer" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM users
WHERE id = #{id}
</select>
<insert id="insert" parameterType="com.example.demo.domain.UserEntity" >
INSERT INTO
users
(userName,passWord,user_sex,nick_name)
VALUES
(#{userName}, #{passWord}, #{userSex},#{nickName})
</insert>
<update id="update" parameterType="com.example.demo.domain.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.Integer" >
DELETE FROM
users
WHERE
id =#{id}
</delete>
</mapper>
User2Mapper.xml配置一样即可
实体类省略
<6>.测试
@RestController
public class UserController {/**
* 多数据库源的测试
*/
/**** start */
@Autowired
private User1Mapper user1Mapper;
@Autowired
private User2Mapper user2Mapper;
@RequestMapping("/getUsers1")
public List<UserEntity> getUsers() {
List<UserEntity> users = user1Mapper.getAll();
return users;
}
@RequestMapping("/getUsers2")
public List<UserEntity> getUsers2() {
List<UserEntity> users = user2Mapper.getAll();
return users;
}
@RequestMapping("/getUser1")
public UserEntity getUser(Integer id) {
UserEntity user = user1Mapper.getOne(id);
return user;
}
@RequestMapping("/getUser2")
public UserEntity getUser2(Integer 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 = "/deleteUser1/{id}")
public void delete(@PathVariable("id") Integer id) {
user1Mapper.delete(id);
}
@RequestMapping(value = "/deleteUser2/{id}")
public void delete2(@PathVariable("id") Integer id) {
user2Mapper.delete(id);
}
/**** end */
}
2.使用注解的方式
其他的不同点参考配置mybatis配置,只做DataSource的编写
数据源配置
@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);
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);
}
}