Springboot整合mybatis的多数据源配置与使用(XM
在上一篇文章springBoot+Hibernate多数据源配置与使用讲述了Springboot整合Hibernate实现多数据源配置,这篇文章则讲述了整合mybatis的情况,对于Hibernate,其自带的各类数据库模板操作方法能够很方便快捷的完成基本的增删改查功能,特点:简单,快捷,而与之相对应的则是它的灵活性就没那么好了,当需要进行复杂的操作(诸如多表查询),Hibernate就有点捉襟见肘了。反观mybatis,由于其直接使用SQL语句完成程序到数据库的相应操作,无论多么简单的操作,你都得写出其完整的SQL语句,因此显得比较繁琐,而在另一方面,由于直接使用SQL语句完成操作,其灵活性不言而喻。至于选择哪一个框架,则视具体的需求而定。
一、创建Springboot项目
创建项目的方式多种多样,可以任意选择,结果都是一样的
<1>直接登陆Spring Initializer页面,在页面选择项目类型(如Maven Project)、Spring boot版本等,填写项目名,添加依赖后,点击“Generate Project”就会下载一个压缩包。下载后,解压缩,在idea或者eclipse中将其打开即可。
<2>在idea中新建一个Maven项目,然后添加jar包依赖,在我之前的一篇文章Spring-datatable-Jpa实现增删改查及分页有一个简单的介绍,需要的初学者可以看下。
<3>在idea中新建一个Spring Initializer项目,一路next,在需要填入项目名的时候,填入即可。
二、POM.xml
pom.xml中导入的依赖项即是项目所需要导入的各种jar包,本文所用到的jar包如下:
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.40</version>
</dependency>
<!--部署热启动依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration> <!--热启动配置-->
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
built标签部分的内容为添加热部署配置,同时还需要加如上标注的热部署依赖jar包,当不需要使用热部署时,这些东西都是不需要的。
三、项目配置文件
在看各类配置文件之前,我们先看下项目的目录结构,这样对整个项目有一个直观的了解。首先,我们来配置application.properties文件,该配置文件可以理解为一个根配置文件,需要在该配置文件中指明下一级的配置文件路径,一般端口,数据源等配置均在该文件中进行配置。本项目有两数据源,因此需要分别配置。项目使用的配置如下:
mybatis.config-locations=classpath:mybatis/config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
spring.datasource.primary.driverClassName = com.mysql.jdbc.Driver
spring.datasource.primary.url = jdbc:mysql://localhost:3306/mybatis1?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.primary.username = root
spring.datasource.primary.password = root
spring.datasource.secondary.driverClassName = com.mysql.jdbc.Driver
spring.datasource.secondary.url = jdbc:mysql://localhost:3306/mybatis2?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.secondary.username = root
spring.datasource.secondary.password = root
前两行指明了mybatis的配置文件位置,以及其mapper对应的.xml位置,接下来的是两个数据源的配置,一个database对应一个数据源,若另一个为oracle数据库也是OK的。
接下来看config.xml文件,其仅作为一个类型的匹配。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
在mapper中的两个.xml文件为java文件夹下的mapper中对应的UserMapper接口,该接口定义一些增删改查语句,并在resources下的mapper文件夹中对应的.xml文件中进行实现,具体内容在下面介绍mapper接口时阐述。
四、后台功能实现代码
由于有两个数据源,因此在application.properties文件中数据源的配置不能使用默认的格式,而自写的数据源格式项目肯定是不认识的,因此需要进行额外配置。
<1>创建配置文件
在com.spring.mybatisxml包下创建datasource包,存放定义数据源java文件。在datasources包下新建DataSource1Config.class和DataSource2Config.class分别定义两个数据源。
DataSource1Config.class :
package com.spring.mybatisxml.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;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.spring.mybatisxml.mapper.mapper1", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class DataSource1Config {
@Bean(name = "primaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "primarySqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/UserMapper1.xml"));
return bean.getObject();
}
@Bean(name = "primaryTransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "primarySqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
DataSources2Config.class :
package com.spring.mybatisxml.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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.spring.mybatisxml.mapper.mapper2", sqlSessionTemplateRef = "secondarySqlSessionTemplate")
public class DataSource2Config {
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondarySqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/UserMapper2.xml"));
return bean.getObject();
}
@Bean(name = "secondaryTransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "secondarySqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
完成了数据源定义后,接下来便是常规的controller层,entity层,对应数据库的mapper层,此处为简略起见,略掉了service层。由于带有了角色权限,而角色一般就那几个,因此建立enums包,在改包新建AuthorityEnum.class文件如下:
package com.spring.mybatisxml.enums;
public enum AuthorityEnum {
manager,registrant,visitor
}
entity实体层,新建User.class文件,内容如下:
package com.spring.mybatisxml.entity;
import com.spring.mybatisxml.enums.AuthorityEnum;
import java.io.Serializable;
public class User implements Serializable {
private int id;
private String userName;
private AuthorityEnum authority;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public AuthorityEnum getAuthority() {
return authority;
}
public void setAuthority(AuthorityEnum authority) {
this.authority = authority;
}
}
controller控制层,新建MainController.class文件,内容如下:
package com.spring.mybatisxml.controller;
import com.alibaba.fastjson.JSONObject;
import com.spring.mybatisxml.entity.User;
import com.spring.mybatisxml.mapper.mapper1.UserMapper1;
import com.spring.mybatisxml.mapper.mapper2.UserMapper2;
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 MainController {
@Autowired
private UserMapper1 userMapper1;
@Autowired
private UserMapper2 userMapper2;
@RequestMapping("/all")
public JSONObject findAll(){
List<User> users1 = userMapper1.findAll();
List<User> users2 = userMapper2.findAll();
users1.addAll(users2);
JSONObject json = new JSONObject();
json.put("data",users1);
return json;
}
/*** 数据库1操作 ***/
@RequestMapping("/find1")
public JSONObject findOne(Integer id){
User user = userMapper1.findOne(id);
JSONObject json = new JSONObject();
json.put("data",user);
return json;
}
@RequestMapping("/add1")
public void addOne(User user){
userMapper1.addOne(user);
}
@RequestMapping("/update1")
public void updateOne(User user){
userMapper1.updateOne(user);
}
@RequestMapping("/del1")
public void delOne(Integer id){
userMapper1.delOne(id);
}
/*** 数据库2操作 ***/
@RequestMapping("/find2")
public JSONObject findOne2(Integer id){
User user = userMapper2.findOne(id);
JSONObject json = new JSONObject();
json.put("data",user);
return json;
}
@RequestMapping("/add2")
public void addOne2(User user){
userMapper2.addOne(user);
}
@RequestMapping("/update2")
public void updateOne2(User user){
userMapper2.updateOne(user);
}
@RequestMapping("/del2")
public void delOne2(Integer id){
userMapper2.delOne(id);
}
}
对与mapper层,由于有两个数据源,因此需要两个接口文件与之对应,如目录结构所示,新建UserMapper1.interface和UserMapper2.interface,内容分别如下:
package com.spring.mybatisxml.mapper.mapper1;
import com.spring.mybatisxml.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Mapper
public interface UserMapper1 {
List<User> findAll();
User findOne(Integer id);
void addOne(User user);
void updateOne(User user);
void delOne(Integer id);
}
package com.spring.mybatisxml.mapper.mapper2;
import com.spring.mybatisxml.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Mapper
public interface UserMapper2 {
List<User> findAll();
User findOne(Integer id);
void addOne(User user);
void updateOne(User user);
void delOne(Integer id);
}
在完成了接口后,接下来该关注的就是其实现了。如目录结构所示,在resources文件夹下新建mybatis文件夹,在该文件夹下新建config.xml文件(没错,就是上文提到的,在application.xml文件中配置路径的config.xml文件)和mapper文件夹,在mapper文件夹下新建UserMapper1.xml和UserMapper2.xml文件,以对上述的UserMapper1.interface和UserMapper2.interface进行实现。其内容分别如下:
<?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.spring.mybatisxml.mapper.mapper1.UserMapper1" > <!--指定mapper位置-->
<resultMap id="BaseResultMap" type="com.spring.mybatisxml.entity.User" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="authority" property="authority" javaType="com.spring.mybatisxml.enums.AuthorityEnum"/>
</resultMap>
<sql id="Base_Column_List" >id, userName, authority</sql>
<select id="findAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM user
</select>
<select id="findOne" resultMap="BaseResultMap">
SELECT * FROM user WHERE id=#{id}
</select>
<insert id="addOne">
INSERT INTO user(userName,authority) VALUES (#{userName},#{authority})
</insert>
<update id="updateOne">
UPDATE user SET userName=#{userName},authority=#{authority} WHERE id=#{id}
</update>
<delete id="delOne">
DELETE FROM user WHERE id=#{id}
</delete>
</mapper>
<?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.spring.mybatisxml.mapper.mapper2.UserMapper2" > <!--指定mapper位置-->
<resultMap id="BaseResultMap" type="com.spring.mybatisxml.entity.User" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="userName" property="userName" jdbcType="VARCHAR" />
<result column="authority" property="authority" javaType="com.spring.mybatisxml.enums.AuthorityEnum"/>
</resultMap>
<sql id="Base_Column_List" >id, userName, authority</sql>
<select id="findAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM user
</select>
<select id="findOne" resultMap="BaseResultMap">
SELECT * FROM user WHERE id=#{id}
</select>
<insert id="addOne">
INSERT INTO user(userName,authority) VALUES (#{userName},#{authority})
</insert>
<update id="updateOne">
UPDATE user SET userName=#{userName},authority=#{authority} WHERE id=#{id}
</update>
<delete id="delOne">
DELETE FROM user WHERE id=#{id}
</delete>
</mapper>
其中的<mapper namespace=.....>为扫描对应的接口,不然它怎么知道对应的是哪一个。
当你完成了上述这些内容的时候,那么就可以见证奇迹的时刻了。看博文可以给你一个整体的理解,以及对某些细节的详解,但是想要完成实现一个项目,看源码往往是很有必要的。
源码链接