Springboot+MybatisPlust+ControllerAdvice ;Mybatis_Plus多数据源,controller统一异常返回
Springboot+MybatisPlus多数据源+controller全局异常返回
1、多数据源
1.1 添加依赖
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- <modelVersion>4.0.0</modelVersion>-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mybatis_plus</groupId>
<artifactId>mybatisplus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatisplus</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>com.mybatiplus</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<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>
<!--添加MybatisPlus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!--添加Mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--Lombok不用写get、set-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
<!--代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>3.4.1</version>
</dependency>
<!--MyBatis Plus 多数据源-->
<!--不造为啥 dynamic-datasource-spring-boot-starter 会依赖这个 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.4.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.4.0</version>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.4.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
1.2 MybatisPlus代码生成器
public class SggCodeGenerator {
public static void main(String[] args) {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/mybatisplus/src/main/java");
gc.setAuthor("ken");
gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setIdType(IdType.ID_WORKER_STR); //主键策略
gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型
gc.setSwagger2(false);//开启Swagger2模式
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/vhr?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(null); //模块名
pc.setParent("com.ken.hr");
pc.setController("controller");
pc.setEntity("entity");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("hr");//对那一张表生成代码
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略
strategy.setEntityLombokModel(true); // lombok 模型 @Accessors(chain = true) setter链式操作
strategy.setRestControllerStyle(true); //restful api风格控制器
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
}
1.3 mapper.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.ken.role.mapper.RoleMapper">
<!--不带条件的语句-->
<select id="testReturnListMap" resultType="java.util.Map">
select id,name,nameZh from role
</select>
<!--带条件的查询语句-->
<select id="testReturnListMapById" resultType="java.util.Map" parameterType="integer">
select id,name from role where 1=1
<if test="id!= null" >
and id=#{id, jdbcType=INTEGER }
</if>
</select>
<!--带参数的存储过程-->
<select id="exePro" parameterType="integer" resultType="java.util.Map" statementType="CALLABLE">
{
call stu_findByid (
#{id,jdbcType=VARCHAR,mode=IN}
)
}
</select>
<!--带参数的存储过程-->
<select id="exeProByName" parameterType="com.ken.role.entity.Role" resultType="java.util.Map" statementType="CALLABLE">
{
call stu_findByid (
#{id,jdbcType=VARCHAR,mode=IN}
)
}
</select>
</mapper>
1.4 dao
package com.ken.role.mapper;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ken.role.entity.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* @author ken
* @since 2021-05-16
*/
@Mapper
public interface RoleMapper extends BaseMapper<Role> {
/**
*
* 查询所有的Role
*
* @return
*/
List<Map<String, Object>> testReturnListMap() ;
/**
*
* 通过ID查询记录
* @param id
* @return
*/
List<Map<String,Object>> testReturnListMapById(@Param("id") Integer id);
/**
*
* 通过ID查询记录
* @param id
* @return
*/
List<Map<String, Object>> exePro(@Param("id") Integer id);
/**
* 通过ID查询记录
* @param role
* @return
*/
@DS("master")
List<Map<String, Object>> exeProByName(Role role);
}
1.5 Yml
server:
port: 9009
mybatis-plus:
mapper-locations: classpath:com/ken/role/mapper/xml/*.xml
configuration:
default-statement-timeout: 3
spring:
application:
name: mybatis_plus
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master: #默认数据源
url: jdbc:mysql://localhost:3306/vhr?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false
username: root
password: root
driver-calss-name: com.mysql.cj.jdbc.Driver
db02:
url: jdbc:mysql://localhost:3306/demo2?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false
username: root
password: root
driver-calss-name: com.mysql.cj.jdbc.Driver
db03:
url: jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useUnicode=true&useSSL=false
username: root
password: root
driver-calss-name: com.mysql.cj.jdbc.Driver
2. 注意点:
-
pom.xml 里面必须增加resources 指定Mapper.xml的位置,不然会提示找不到mapper
-
在Yml配置里面里面增加mybatis locations 也可以
-
controller需要在启动类加上
-
controller全局异常需要
@Bean MyExceptionHandler myExceptionHandler(){ return new MyExceptionHandler(); }
不然全局异常类和controller要放到一个package上面