目录
一、整合Mybatis
配置文件
pom.xml
application.yml
jdbc.properties
generatorConfig.xml
启动类
测试
二、整合Mybatis-plus
Mybatis-plus
新建项目
pom.xml
application.yml
在项目导入mybatis-plus的代码生成的类
完成基本增删改查方法开发
三、Mybatisplus中使用Mybatis实现多表连查的功能
一、整合Mybatis
确保项目启动成功
配置文件
pom.xml
修改mysql版本
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
</dependencies>
<configuration>
<overwrite>true</overwrite>
</configuration>
</plugin>
application.yml
mybatis:
mapper-locations: classpath:mappers/**/*.xml
type-aliases-package: com.maomao.pringbootmybatis.model
server:
port: 8082
spring:
application:
name: spbootmybatis
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
password: 123456
username: root
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="jdbc.properties"/>
<!--指定数据库jdbc驱动jar包的位置-->
<classPathEntry location="F:\Maven\mvn_repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/>
<!-- 一个数据库一个context -->
<context id="infoGuardian">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 01 指定javaBean生成的位置 -->
<!-- targetPackage:指定生成的model生成所在的包名 -->
<!-- targetProject:指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="com.maomao.spbootmybatis.model"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="false"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!-- 02 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.maomao.spbootmybatis.mapper"
targetProject="src/main/resources/mappers">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 03 生成XxxMapper接口 -->
<!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
<!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
<!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.maomao.spbootmybatis.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 配置表信息 -->
<!-- schema即为数据库名 -->
<!-- tableName为对应的数据库表 -->
<!-- domainObjectName是要生成的实体类 -->
<!-- enable*ByExample是否生成 example类 -->
<!--<table schema="" tableName="t_book" domainObjectName="Book"-->
<!--enableCountByExample="false" enableDeleteByExample="false"-->
<!--enableSelectByExample="false" enableUpdateByExample="false">-->
<!--<!– 忽略列,不生成bean 字段 –>-->
<!--<!– <ignoreColumn column="FRED" /> –>-->
<!--<!– 指定列的java数据类型 –>-->
<!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>-->
<!--</table>-->
<table schema="" tableName="t_mvc_book" domainObjectName="Book"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
</context>
</generatorConfiguration>
启动类
package com.maomao.spbootmybatis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//完成对mapper接口的扫描
@MapperScan("com.maomao.spbootmybatis.mapper")
//开启对事物的管理
@EnableTransactionManagement
@SpringBootApplication
public class SpbootmybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpbootmybatisApplication.class, args);
}
}
测试
利用Eolink进行测试
二、整合Mybatis-plus
Mybatis-plus
官网
MyBatis-Plus
①企业中大量使用
②减少*Mapper.xml中的SQL编写
③与若依相比,略为繁琐,但是可移植性极强
新建项目
勾选五个组件:
lombok、web、jdbc、mybatis-plus、MySQL driver
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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.maomao</groupId>
<artifactId>springbootmp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootmp</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.7.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<!-- 添加额外的pom依赖 ,用于mybatis plus代码生成 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>3.4.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.3.7.RELEASE</version>
<configuration>
<mainClass>com.maomao.springbootmp.SpringbootmpApplication</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
application.yml
server:
port: 8082
spring:
application:
name: springbootmp
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
password: 123456
username: root
logging:
level:
com.maomao.springbootmp: debug
mybatis-plus:
mapper-locations: classpath:mappers/**/*.xml
type-aliases-package: com.maomao.springbootmp.book.model
在项目导入mybatis-plus的代码生成的类
copy官网
注意事项:
(1)需要更改代码生成的module名
(2)需要设置父包的位置
(3)要预先创建好mappers的文件夹
MPGenerator.java
package com.maomao.springbootmp.mp;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* mybatis-plus代码生成
*/
public class MPGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip);
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
if ("quit".equals(ipt)) return "";
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 1.全局配置
GlobalConfig gc = new GlobalConfig();
// System.getProperty("user.dir")指的是工作区间,就是Springboot01
String projectPath = System.getProperty("user.dir") + "/springbootmp";
System.out.println(projectPath);
gc.setOutputDir(projectPath + "/src/main/java");
gc.setOpen(false);
gc.setBaseResultMap(true);//生成BaseResultMap
gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
//gc.setSwagger2(true); //实体属性 Swagger2 注解
gc.setAuthor("maomao");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
gc.setIdType(IdType.AUTO);
mpg.setGlobalConfig(gc);
// 2.数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 3.包配置
PackageConfig pc = new PackageConfig();
String moduleName = scanner("模块名(quit退出,表示没有模块名)");
if (StringUtils.isNotBlank(moduleName)) {
pc.setModuleName(moduleName);
}
// 设置父包
pc.setParent("com.maomao.springbootmp")
.setMapper("mapper")
.setService("service")
.setController("controller")
.setEntity("model");
mpg.setPackageInfo(pc);
// 4.自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
if (StringUtils.isNotBlank(pc.getModuleName())) {
return projectPath + "/src/main/resources/mappers/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
} else {
return projectPath + "/src/main/resources/mappers/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 5.策略配置
StrategyConfig strategy = new StrategyConfig();
// 表名生成策略(下划线转驼峰命名)
strategy.setNaming(NamingStrategy.underline_to_camel);
// 列名生成策略(下划线转驼峰命名)
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 是否启动Lombok配置
strategy.setEntityLombokModel(true);
// 是否启动REST风格配置
strategy.setRestControllerStyle(true);
// 自定义实体父类strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
// 自定义service父接口strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
// 自定义service实现类strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
// 自定义mapper接口strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
strategy.setSuperEntityColumns("id");
// 写于父类中的公共字段plus
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
//表名前缀(可变参数):“t_”或”“t_模块名”,例如:t_user或t_sys_user
strategy.setTablePrefix("t_", "t_sys_");
//strategy.setTablePrefix(scanner("请输入表前缀"));
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 执行
mpg.execute();
}
}
运行:
mybatis-plus接口的讲解
(1)basemapper/baseservice都已经封装好了基本的增删改查及基本使用
(2)QueryWrapper的使用,可以构建查询条件,减少配置文件xml的sql编写
完成基本增删改查方法开发
MvcBookController.java
package com.maomao.springbootmp.book.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.maomao.springbootmp.book.model.MvcBook;
import com.maomao.springbootmp.book.service.MvcBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author maomao
* @since 2022-12-02
*/
@RestController
@RequestMapping("/mp")
public class MvcBookController {
@Autowired
private MvcBookService bookService;
// 查询所有
@GetMapping("/list")
public List<MvcBook> list(){
return bookService.list();
}
// 按条件查询
@GetMapping("/listByCondition")
public List<MvcBook> listByCondition(MvcBook book){
// 如果使用的是Mybatis,那么我们需要写SQL语句,而MP不需要
QueryWrapper qw=new QueryWrapper();
qw.like("bname",book.getBname());
return bookService.list();
}
// 查询单个
@GetMapping("/get")
public MvcBook get(MvcBook book){
return bookService.getById(book.getBid());
}
// 增加
@PutMapping("/add")
public boolean add(MvcBook book){
return bookService.save(book);
}
// 删除
@PutMapping("/delete")
public boolean delete(MvcBook book){
return bookService.removeById(book.getBid());
}
// 修改
@PutMapping("/update")
public boolean update(MvcBook book){
return bookService.saveOrUpdate(book);
}
}
测试
三、Mybatisplus中使用Mybatis实现多表连查的功能
用户、角色、用户角色中间表连表查询的案例
MvcBookMappper.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.maomao.springbootmp.book.mapper.MvcBookMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="com.maomao.springbootmp.book.model.MvcBook">
<id column="bid" property="bid" />
<result column="bname" property="bname" />
<result column="price" property="price" />
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
bid, bname, price
</sql>
<!--注意mybatisplus中的配置文件默认也是没有生成对应增删改查的SQL语句的,因为mp是顶层接口都封装好了,调用即可-->
<select id="queryUserRole" parameterType="java.util.Map" resultType="java.util.Map">
SELECT u.username,r.rolename FROM t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
where u.userid = ur.userid and ur.roleid = r.roleid
<if test="username != null and username != ''">
and u.username = #{username}
</if>
</select>
</mapper>
MvcBookMapper.java
package com.maomao.springbootmp.book.mapper;
import com.maomao.springbootmp.book.model.MvcBook;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author maomao
* @since 2022-12-02
*/
@Repository
public interface MvcBookMapper extends BaseMapper<MvcBook> {
List<Map> queryUserRole(Map map);
}
MvcBookService.java
package com.maomao.springbootmp.book.service;
import com.maomao.springbootmp.book.model.MvcBook;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务类
* </p>
*
* @author maomao
* @since 2022-12-02
*/
public interface MvcBookService extends IService<MvcBook> {
List<Map> queryUserRole(Map map);
}
MvcBookServiceImpl.java
package com.maomao.springbootmp.book.service.impl;
import com.maomao.springbootmp.book.model.MvcBook;
import com.maomao.springbootmp.book.mapper.MvcBookMapper;
import com.maomao.springbootmp.book.service.MvcBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务实现类
* </p>
*
* @author maomao
* @since 2022-12-02
*/
@Service
public class MvcBookServiceImpl extends ServiceImpl<MvcBookMapper, MvcBook> implements MvcBookService {
@Autowired
private MvcBookMapper bookMapper;
@Override
public List<Map> queryUserRole(Map map) {
return bookMapper.queryUserRole(map);
}
}
MvcBookController.java
//多表联查 ,用户姓名对应角色的功能,论证mybatis是一样可以使用mybatis功能
@GetMapping("/queryUserRole")
public List<Map> queryUserRole(String uname){
// 前端传了一个zs
Map map = new HashMap();
map.put("username",uname);
return bookService.queryUserRole(map);
}
用Eolink进行测试