目录
三,Mybatisplus中使用Mybatis实现多表联查的功能
(不会还有人不会创建吧?赶紧去看看上一篇)
创建成功
在以前我们Spring整合Mybatis时会需要一系列的配置,
如Spring-Mybatis.xml
jdbc.properties
datasource
........
而现在当我们勾选了插件创建完项目后就会自动配置
修改配置为属于自己的
经测试发现生成的mysql的pom依赖可能会存在矛盾问题,所以这里给他降了版本,使用5.1.44版
generateconfig.xml
修改指定sql映射文件生成的位置
- "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"/>
-
-
- <classPathEntry
- location="F:\cangku\mvn_repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/>
-
-
- <context id="infoGuardian">
-
- <commentGenerator>
- <property name="suppressAllComments" value="true"/>
- <property name="suppressDate" value="true"/>
- commentGenerator>
-
-
- <jdbcConnection driverClass="${jdbc.driver}"
- connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
-
-
- <javaTypeResolver>
-
- <property name="forceBigDecimals" value="false"/>
- javaTypeResolver>
-
-
-
-
- <javaModelGenerator targetPackage="com.ljj.springbootmybatis.model"
- targetProject="src/main/java">
-
- <property name="enableSubPackages" value="false"/>
-
- <property name="constructorBased" value="true"/>
-
- <property name="trimStrings" value="false"/>
-
- <property name="immutable" value="false"/>
- javaModelGenerator>
-
-
- <sqlMapGenerator targetPackage="com.ljj.springbootmybatis.mapper"
- targetProject="src/main/resources/mappers">
-
- <property name="enableSubPackages" value="false"/>
- sqlMapGenerator>
-
-
-
-
-
- <javaClientGenerator targetPackage="com.ljj.springbootmybatis.mapper"
- targetProject="src/main/java" type="XMLMAPPER">
-
- <property name="enableSubPackages" value="false"/>
- javaClientGenerator>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- <table schema="" tableName="t_mvc_book" domainObjectName="Book"
- enableCountByExample="false" enableDeleteByExample="false"
- enableSelectByExample="false" enableUpdateByExample="false">
- table>
-
-
- context>
- generatorConfiguration>
application.yml
- mybatis:
- mapper-locations: classpath:mappers/**/*.xml
- type-aliases-package: com.ljj.springbootmybatis.model
- server:
- port: 8080
- spring:
- application:
- name: springbootmybatis
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- name: defaultDataSource
- password: 123456
- url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
- 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
源码:
- <groupId>org.mybatis.generatorgroupId>
- <artifactId>mybatis-generator-maven-pluginartifactId>
- <version>1.3.2version>
- <dependencies>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>5.1.44version>
- dependency>
- dependencies>
- <configuration>
- <overwrite>trueoverwrite>
- configuration>
-
选择Maven
生成成功
1.BookMapper.xml
2. application.yml
统一的时候即使不写方法中的全路径也没关系,只写Book
- package com.ljj.springbootmybatis.web;
-
- import com.ljj.springbootmybatis.mapper.BookMapper;
- import com.ljj.springbootmybatis.model.Book;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.DeleteMapping;
- import org.springframework.web.bind.annotation.PutMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import java.text.Bidi;
- import java.util.List;
-
- /**
- * @author ljj
- * @site www.xiaomage.com
- * @company
- * @create 2022-11-04 20:06
- */
- @RestController
- @RequestMapping("mybatis")
- public class BookController {
- @Autowired
- private BookMapper bookMapper;
- // 查询
- @RequestMapping("/get")
- public Book get(Integer bid){
- return bookMapper.selectByPrimaryKey(bid);
- }
-
- // 删除
- @DeleteMapping("/delete")
- public int delete(Integer bid){
- return bookMapper.deleteByPrimaryKey(bid);
- }
-
- // 新增
- @PutMapping("/add")
- public int add(Book book){
- return bookMapper.insertSelective(book);
- }
- }
在项目启动类中
@MapperScan("com.ljj.springbootmybatis.mapper")
@EnableTransactionManagement
运行项目
按bid进行查询
删除bid为40的内容,影响行数为1
再次查询bid为40的内容,已删除,查询为空了
再增加一条bid为40的
再次查询bid为40的,显示内容为我们测试增加方法中增加的数据
官网:MyBatis-Plus
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1.企业中大量使用
2.极大的减少*Mapoer.xml中的SQL 编写
3.与若依相比略微繁琐,但是可移植性极强
2.3 开始整合
创建Springboot项目,与上一目录中的创建项目方法一致,将mybatis插件换成mybatis plus插件即可
-
-
com.baomidou -
mybatis-plus-generator -
3.4.1 -
-
-
org.freemarker -
freemarker -
2.3.31 -
-
-
mysql -
mysql-connector-java -
5.1.44 -
- server:
- port: 8080
- spring:
- application:
- name: springbootmp
- datasource:
- driver-class-name: com.mysql.jdbc.Driver
- name: defaultDataSource
- password: 123456
- url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
- username: root
- mybatis-plus:
- mapper-locations: classpath:mappers/**/*.xml
- type-aliases-package: com.ljj.springbootmp.book.model
官网中有编写代码生成器教学
注意修改几处
- package com.ljj.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 {
-
- /**
- *
- * 读取控制台内容
- *
- */
- 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")指的是工作区间,就是ljj20222203
- 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("小刘");//发开者
-
- // 自定义文件命名,注意 %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.ljj.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
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();
- }
- }
执行此类中的main方法
生成成功
当我们打开生成的文件夹时,会发现mapper层以及service中是空的,但是我们可以点开此类继承的接口,方法全部被封装在里面了,继续测试增删改查
- package com.ljj.springbootmp.book.controller;
-
-
- import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
- import com.ljj.springbootmp.book.model.MvcBook;
- import com.ljj.springbootmp.book.service.MvcBookService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.*;
-
- import java.awt.print.Book;
- import java.util.List;
-
- /**
- *
- * 前端控制器
- *
- *
- * @author 小刘
- * @since 2022-11-05
- */
- @RestController
- @RequestMapping("/mp")
- public class MvcBookController {
- @Autowired
- private MvcBookService bookService;
-
- @GetMapping("/list")
- public List
list(){ - return bookService.list();
- }
-
- //查询所有
- @GetMapping("/listByCondition")
- public List
listByCondition(MvcBook book){ - // 如果使用的是Mybatis 那么我们就需要写sql语句,
- // select from t_mvc where bname like '%2%' mapper.xml
- QueryWrapper qw = new QueryWrapper();
- qw.like("bname",book.getBname());
- return bookService.list(qw);
- }
-
- //查询单个
- @GetMapping("/get")
- public MvcBook get(MvcBook book){
- return bookService.getById(book.getBid());
- }
-
- //增加
- @PutMapping("/add")
- public boolean add(MvcBook book){
- return bookService.save(book);
- }
-
- //删除
- @DeleteMapping("/delete")
- public boolean delete(MvcBook book){
- return bookService.removeById(book.getBid());
- }
-
- //修改
- @PostMapping("/update")
- public boolean update(MvcBook book){
- return bookService.saveOrUpdate(book);
- }
-
- }
list方法查询全部
多表联查的功能,论证Mybatisplus是一样可以使用Mybatis功能的
- 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 and u.username = r.roleid
t_shiro_role
t_shiro_user
t_shiro_user_role
- "1.0" encoding="UTF-8"?>
- mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.ycx.springbootmp.book.mapper.MvcBookMapper">
-
-
- <resultMap id="BaseResultMap" type="com.ycx.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>
- <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>
List<Map> queryUserRole(Map map);
List<Map> queryUserRole(Map map);
- @Autowired
- private MvcBookMapper bookMapper;
-
- @Override
- public List<Map> queryUserRole(Map map) {
- return bookMapper.queryUserRole(map);
- }
- //多表联查 ,用户姓名对应角色的功能,论证mybatis是一样可以使用mybatis功能
- @GetMapping("/queryUserRole")
- public List
- // 前端传了一个zs
- Map map = new HashMap();
- map.put("username",uname);
- return bookService.queryUserRole(map);
- }