mybatis 配置多数据源 java_Springboot整合mybatis的多数据源配置与使用(XML版)

在上一篇文章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包如下:

org.mybatis.spring.boot

mybatis-spring-boot-starter

1.3.1

org.springframework.boot

spring-boot-starter-web

mysql

mysql-connector-java

runtime

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-test

test

com.alibaba

fastjson

1.2.40

org.springframework.boot

spring-boot-devtools

true

org.springframework.boot

spring-boot-maven-plugin

true

true

built标签部分的内容为添加热部署配置,同时还需要加如上标注的热部署依赖jar包,当不需要使用热部署时,这些东西都是不需要的。

三、项目配置文件

在看各类配置文件之前,我们先看下项目的目录结构,这样对整个项目有一个直观的了解。

6291068f130c

首先,我们来配置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文件,其仅作为一个类型的匹配。

在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 users1 = userMapper1.findAll();

List 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 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 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进行实现。其内容分别如下:

id, userName, authority

SELECT

FROM user

SELECT * FROM user WHERE id=#{id}

INSERT INTO user(userName,authority) VALUES (#{userName},#{authority})

UPDATE user SET userName=#{userName},authority=#{authority} WHERE id=#{id}

DELETE FROM user WHERE id=#{id}

id, userName, authority

SELECT

FROM user

SELECT * FROM user WHERE id=#{id}

INSERT INTO user(userName,authority) VALUES (#{userName},#{authority})

UPDATE user SET userName=#{userName},authority=#{authority} WHERE id=#{id}

DELETE FROM user WHERE id=#{id}

其中的为扫描对应的接口,不然它怎么知道对应的是哪一个。

当你完成了上述这些内容的时候,那么就可以见证奇迹的时刻了。看博文可以给你一个整体的理解,以及对某些细节的详解,但是想要完成实现一个项目,看源码往往是很有必要的。

源码链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值