• SSM和SpringBoot整合


    目录

    一、整合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版本

    1. <dependency>
    2. <groupId>mysqlgroupId>
    3. <artifactId>mysql-connector-javaartifactId>
    4. <version>5.1.44version>
    5. dependency>

    1. <plugin>
    2. <groupId>org.mybatis.generatorgroupId>
    3. <artifactId>mybatis-generator-maven-pluginartifactId>
    4. <version>1.3.2version>
    5. <dependencies>
    6. <dependency>
    7. <groupId>mysqlgroupId>
    8. <artifactId>mysql-connector-javaartifactId>
    9. <version>5.1.44version>
    10. dependency>
    11. dependencies>
    12. <configuration>
    13. <overwrite>trueoverwrite>
    14. configuration>
    15. plugin>

     application.yml

    1. mybatis:
    2. mapper-locations: classpath:mappers/**/*.xml
    3. type-aliases-package: com.maomao.pringbootmybatis.model
    4. server:
    5. port: 8082
    6. spring:
    7. application:
    8. name: spbootmybatis
    9. datasource:
    10. driver-class-name: com.mysql.jdbc.Driver
    11. url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
    12. password: 123456
    13. username: root

    jdbc.properties

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
    3. jdbc.username=root
    4. jdbc.password=123456

    generatorConfig.xml

    1. "1.0" encoding="UTF-8" ?>
    2. generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    3. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
    4. <generatorConfiguration>
    5. <properties resource="jdbc.properties"/>
    6. <classPathEntry location="F:\Maven\mvn_repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/>
    7. <context id="infoGuardian">
    8. <commentGenerator>
    9. <property name="suppressAllComments" value="true"/>
    10. <property name="suppressDate" value="true"/>
    11. commentGenerator>
    12. <jdbcConnection driverClass="${jdbc.driver}"
    13. connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
    14. <javaTypeResolver>
    15. <property name="forceBigDecimals" value="false"/>
    16. javaTypeResolver>
    17. <javaModelGenerator targetPackage="com.maomao.spbootmybatis.model"
    18. targetProject="src/main/java">
    19. <property name="enableSubPackages" value="false"/>
    20. <property name="constructorBased" value="true"/>
    21. <property name="trimStrings" value="false"/>
    22. <property name="immutable" value="false"/>
    23. javaModelGenerator>
    24. <sqlMapGenerator targetPackage="com.maomao.spbootmybatis.mapper"
    25. targetProject="src/main/resources/mappers">
    26. <property name="enableSubPackages" value="false"/>
    27. sqlMapGenerator>
    28. <javaClientGenerator targetPackage="com.maomao.spbootmybatis.mapper"
    29. targetProject="src/main/java" type="XMLMAPPER">
    30. <property name="enableSubPackages" value="false"/>
    31. javaClientGenerator>
    32. <table schema="" tableName="t_mvc_book" domainObjectName="Book"
    33. enableCountByExample="false" enableDeleteByExample="false"
    34. enableSelectByExample="false" enableUpdateByExample="false">
    35. table>
    36. context>
    37. generatorConfiguration>

    启动类

    1. package com.maomao.spbootmybatis;
    2. import org.mybatis.spring.annotation.MapperScan;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.autoconfigure.SpringBootApplication;
    5. import org.springframework.transaction.annotation.EnableTransactionManagement;
    6. //完成对mapper接口的扫描
    7. @MapperScan("com.maomao.spbootmybatis.mapper")
    8. //开启对事物的管理
    9. @EnableTransactionManagement
    10. @SpringBootApplication
    11. public class SpbootmybatisApplication {
    12. public static void main(String[] args) {
    13. SpringApplication.run(SpbootmybatisApplication.class, args);
    14. }
    15. }

    测试

    利用Eolink进行测试

    二、整合Mybatis-plus

    Mybatis-plus

    官网

    MyBatis-Plus

    ①企业中大量使用

    ②减少*Mapper.xml中的SQL编写

    ③与若依相比,略为繁琐,但是可移植性极强

    新建项目

    勾选五个组件:

    lombok、web、jdbc、mybatis-plus、MySQL driver

    pom.xml

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <groupId>com.maomaogroupId>
    6. <artifactId>springbootmpartifactId>
    7. <version>0.0.1-SNAPSHOTversion>
    8. <name>springbootmpname>
    9. <description>Demo project for Spring Bootdescription>
    10. <properties>
    11. <java.version>1.8java.version>
    12. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    13. <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
    14. <spring-boot.version>2.3.7.RELEASEspring-boot.version>
    15. properties>
    16. <dependencies>
    17. <dependency>
    18. <groupId>org.springframework.bootgroupId>
    19. <artifactId>spring-boot-starter-jdbcartifactId>
    20. dependency>
    21. <dependency>
    22. <groupId>org.springframework.bootgroupId>
    23. <artifactId>spring-boot-starter-webartifactId>
    24. dependency>
    25. <dependency>
    26. <groupId>com.baomidougroupId>
    27. <artifactId>mybatis-plus-boot-starterartifactId>
    28. <version>3.4.2version>
    29. dependency>
    30. <dependency>
    31. <groupId>com.baomidougroupId>
    32. <artifactId>mybatis-plus-generatorartifactId>
    33. <version>3.4.1version>
    34. dependency>
    35. <dependency>
    36. <groupId>org.freemarkergroupId>
    37. <artifactId>freemarkerartifactId>
    38. <version>2.3.31version>
    39. dependency>
    40. <dependency>
    41. <groupId>mysqlgroupId>
    42. <artifactId>mysql-connector-javaartifactId>
    43. <version>5.1.44version>
    44. dependency>
    45. <dependency>
    46. <groupId>org.projectlombokgroupId>
    47. <artifactId>lombokartifactId>
    48. <optional>trueoptional>
    49. dependency>
    50. <dependency>
    51. <groupId>org.springframework.bootgroupId>
    52. <artifactId>spring-boot-starter-testartifactId>
    53. <scope>testscope>
    54. <exclusions>
    55. <exclusion>
    56. <groupId>org.junit.vintagegroupId>
    57. <artifactId>junit-vintage-engineartifactId>
    58. exclusion>
    59. exclusions>
    60. dependency>
    61. <dependency>
    62. <groupId>com.baomidougroupId>
    63. <artifactId>mybatis-plus-coreartifactId>
    64. <version>3.4.2version>
    65. <scope>compilescope>
    66. dependency>
    67. dependencies>
    68. <dependencyManagement>
    69. <dependencies>
    70. <dependency>
    71. <groupId>org.springframework.bootgroupId>
    72. <artifactId>spring-boot-dependenciesartifactId>
    73. <version>${spring-boot.version}version>
    74. <type>pomtype>
    75. <scope>importscope>
    76. dependency>
    77. dependencies>
    78. dependencyManagement>
    79. <build>
    80. <plugins>
    81. <plugin>
    82. <groupId>org.apache.maven.pluginsgroupId>
    83. <artifactId>maven-compiler-pluginartifactId>
    84. <version>3.8.1version>
    85. <configuration>
    86. <source>1.8source>
    87. <target>1.8target>
    88. <encoding>UTF-8encoding>
    89. configuration>
    90. plugin>
    91. <plugin>
    92. <groupId>org.springframework.bootgroupId>
    93. <artifactId>spring-boot-maven-pluginartifactId>
    94. <version>2.3.7.RELEASEversion>
    95. <configuration>
    96. <mainClass>com.maomao.springbootmp.SpringbootmpApplicationmainClass>
    97. configuration>
    98. <executions>
    99. <execution>
    100. <id>repackageid>
    101. <goals>
    102. <goal>repackagegoal>
    103. goals>
    104. execution>
    105. executions>
    106. plugin>
    107. plugins>
    108. build>
    109. project>

    application.yml

    1. server:
    2. port: 8082
    3. spring:
    4. application:
    5. name: springbootmp
    6. datasource:
    7. driver-class-name: com.mysql.jdbc.Driver
    8. url: jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8
    9. password: 123456
    10. username: root
    11. logging:
    12. level:
    13. com.maomao.springbootmp: debug
    14. mybatis-plus:
    15. mapper-locations: classpath:mappers/**/*.xml
    16. type-aliases-package: com.maomao.springbootmp.book.model

    在项目导入mybatis-plus的代码生成的类

    copy官网

    注意事项:

    (1)需要更改代码生成的module名

    (2)需要设置父包的位置

    (3)要预先创建好mappers的文件夹

    MPGenerator.java

    1. package com.maomao.springbootmp.mp;
    2. import com.baomidou.mybatisplus.annotation.DbType;
    3. import com.baomidou.mybatisplus.annotation.IdType;
    4. import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
    5. import com.baomidou.mybatisplus.core.toolkit.StringPool;
    6. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
    7. import com.baomidou.mybatisplus.generator.AutoGenerator;
    8. import com.baomidou.mybatisplus.generator.InjectionConfig;
    9. import com.baomidou.mybatisplus.generator.config.*;
    10. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
    11. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
    12. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    13. import java.util.ArrayList;
    14. import java.util.List;
    15. import java.util.Scanner;
    16. /**
    17. * mybatis-plus代码生成
    18. */
    19. public class MPGenerator {
    20. /**
    21. *

    22. * 读取控制台内容
    23. *

    24. */
    25. public static String scanner(String tip) {
    26. Scanner scanner = new Scanner(System.in);
    27. StringBuilder help = new StringBuilder();
    28. help.append("请输入" + tip);
    29. System.out.println(help.toString());
    30. if (scanner.hasNext()) {
    31. String ipt = scanner.next();
    32. if (StringUtils.isNotBlank(ipt)) {
    33. if ("quit".equals(ipt)) return "";
    34. return ipt;
    35. }
    36. }
    37. throw new MybatisPlusException("请输入正确的" + tip + "!");
    38. }
    39. public static void main(String[] args) {
    40. // 代码生成器
    41. AutoGenerator mpg = new AutoGenerator();
    42. // 1.全局配置
    43. GlobalConfig gc = new GlobalConfig();
    44. // System.getProperty("user.dir")指的是工作区间,就是Springboot01
    45. String projectPath = System.getProperty("user.dir") + "/springbootmp";
    46. System.out.println(projectPath);
    47. gc.setOutputDir(projectPath + "/src/main/java");
    48. gc.setOpen(false);
    49. gc.setBaseResultMap(true);//生成BaseResultMap
    50. gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
    51. gc.setEnableCache(false);// XML 二级缓存
    52. gc.setBaseResultMap(true);// XML ResultMap
    53. gc.setBaseColumnList(true);// XML columList
    54. //gc.setSwagger2(true); //实体属性 Swagger2 注解
    55. gc.setAuthor("maomao");
    56. // 自定义文件命名,注意 %s 会自动填充表实体属性!
    57. gc.setMapperName("%sMapper");
    58. gc.setXmlName("%sMapper");
    59. gc.setServiceName("%sService");
    60. gc.setServiceImplName("%sServiceImpl");
    61. gc.setControllerName("%sController");
    62. gc.setIdType(IdType.AUTO);
    63. mpg.setGlobalConfig(gc);
    64. // 2.数据源配置
    65. DataSourceConfig dsc = new DataSourceConfig();
    66. dsc.setDbType(DbType.MYSQL);
    67. dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_ssm?useUnicode=true&characterEncoding=UTF-8");
    68. dsc.setDriverName("com.mysql.jdbc.Driver");
    69. dsc.setUsername("root");
    70. dsc.setPassword("123456");
    71. mpg.setDataSource(dsc);
    72. // 3.包配置
    73. PackageConfig pc = new PackageConfig();
    74. String moduleName = scanner("模块名(quit退出,表示没有模块名)");
    75. if (StringUtils.isNotBlank(moduleName)) {
    76. pc.setModuleName(moduleName);
    77. }
    78. // 设置父包
    79. pc.setParent("com.maomao.springbootmp")
    80. .setMapper("mapper")
    81. .setService("service")
    82. .setController("controller")
    83. .setEntity("model");
    84. mpg.setPackageInfo(pc);
    85. // 4.自定义配置
    86. InjectionConfig cfg = new InjectionConfig() {
    87. @Override
    88. public void initMap() {
    89. // to do nothing
    90. }
    91. };
    92. // 如果模板引擎是 freemarker
    93. String templatePath = "/templates/mapper.xml.ftl";
    94. // 自定义输出配置
    95. List focList = new ArrayList<>();
    96. // 自定义配置会被优先输出
    97. focList.add(new FileOutConfig(templatePath) {
    98. @Override
    99. public String outputFile(TableInfo tableInfo) {
    100. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
    101. if (StringUtils.isNotBlank(pc.getModuleName())) {
    102. return projectPath + "/src/main/resources/mappers/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
    103. } else {
    104. return projectPath + "/src/main/resources/mappers/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
    105. }
    106. }
    107. });
    108. cfg.setFileOutConfigList(focList);
    109. mpg.setCfg(cfg);
    110. // 配置模板
    111. TemplateConfig templateConfig = new TemplateConfig();
    112. templateConfig.setXml(null);
    113. mpg.setTemplate(templateConfig);
    114. // 5.策略配置
    115. StrategyConfig strategy = new StrategyConfig();
    116. // 表名生成策略(下划线转驼峰命名)
    117. strategy.setNaming(NamingStrategy.underline_to_camel);
    118. // 列名生成策略(下划线转驼峰命名)
    119. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    120. // 是否启动Lombok配置
    121. strategy.setEntityLombokModel(true);
    122. // 是否启动REST风格配置
    123. strategy.setRestControllerStyle(true);
    124. // 自定义实体父类strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
    125. // 自定义service父接口strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
    126. // 自定义service实现类strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
    127. // 自定义mapper接口strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
    128. strategy.setSuperEntityColumns("id");
    129. // 写于父类中的公共字段plus
    130. strategy.setSuperEntityColumns("id");
    131. strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
    132. strategy.setControllerMappingHyphenStyle(true);
    133. //表名前缀(可变参数):“t_”或”“t_模块名”,例如:t_user或t_sys_user
    134. strategy.setTablePrefix("t_", "t_sys_");
    135. //strategy.setTablePrefix(scanner("请输入表前缀"));
    136. mpg.setStrategy(strategy);
    137. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    138. // 执行
    139. mpg.execute();
    140. }
    141. }

    运行:

    mybatis-plus接口的讲解 

    (1)basemapper/baseservice都已经封装好了基本的增删改查及基本使用

    (2)QueryWrapper的使用,可以构建查询条件,减少配置文件xml的sql编写

     完成基本增删改查方法开发

    MvcBookController.java

    1. package com.maomao.springbootmp.book.controller;
    2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    3. import com.maomao.springbootmp.book.model.MvcBook;
    4. import com.maomao.springbootmp.book.service.MvcBookService;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.web.bind.annotation.GetMapping;
    7. import org.springframework.web.bind.annotation.PutMapping;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.RestController;
    10. import java.util.List;
    11. /**
    12. *

    13. * 前端控制器
    14. *

    15. *
    16. * @author maomao
    17. * @since 2022-12-02
    18. */
    19. @RestController
    20. @RequestMapping("/mp")
    21. public class MvcBookController {
    22. @Autowired
    23. private MvcBookService bookService;
    24. // 查询所有
    25. @GetMapping("/list")
    26. public List list(){
    27. return bookService.list();
    28. }
    29. // 按条件查询
    30. @GetMapping("/listByCondition")
    31. public List listByCondition(MvcBook book){
    32. // 如果使用的是Mybatis,那么我们需要写SQL语句,而MP不需要
    33. QueryWrapper qw=new QueryWrapper();
    34. qw.like("bname",book.getBname());
    35. return bookService.list();
    36. }
    37. // 查询单个
    38. @GetMapping("/get")
    39. public MvcBook get(MvcBook book){
    40. return bookService.getById(book.getBid());
    41. }
    42. // 增加
    43. @PutMapping("/add")
    44. public boolean add(MvcBook book){
    45. return bookService.save(book);
    46. }
    47. // 删除
    48. @PutMapping("/delete")
    49. public boolean delete(MvcBook book){
    50. return bookService.removeById(book.getBid());
    51. }
    52. // 修改
    53. @PutMapping("/update")
    54. public boolean update(MvcBook book){
    55. return bookService.saveOrUpdate(book);
    56. }
    57. }

    测试

     三、Mybatisplus中使用Mybatis实现多表连查的功能

     用户、角色、用户角色中间表连表查询的案例

    MvcBookMappper.xml

    1. "1.0" encoding="UTF-8"?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    3. <mapper namespace="com.maomao.springbootmp.book.mapper.MvcBookMapper">
    4. <resultMap id="BaseResultMap" type="com.maomao.springbootmp.book.model.MvcBook">
    5. <id column="bid" property="bid" />
    6. <result column="bname" property="bname" />
    7. <result column="price" property="price" />
    8. resultMap>
    9. <sql id="Base_Column_List">
    10. bid, bname, price
    11. sql>
    12. <select id="queryUserRole" parameterType="java.util.Map" resultType="java.util.Map">
    13. SELECT u.username,r.rolename FROM t_shiro_user u,t_shiro_user_role ur,t_shiro_role r
    14. where u.userid = ur.userid and ur.roleid = r.roleid
    15. <if test="username != null and username != ''">
    16. and u.username = #{username}
    17. if>
    18. select>
    19. mapper>

    MvcBookMapper.java

    1. package com.maomao.springbootmp.book.mapper;
    2. import com.maomao.springbootmp.book.model.MvcBook;
    3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    4. import org.springframework.stereotype.Repository;
    5. import java.util.List;
    6. import java.util.Map;
    7. /**
    8. *

    9. * Mapper 接口
    10. *

    11. *
    12. * @author maomao
    13. * @since 2022-12-02
    14. */
    15. @Repository
    16. public interface MvcBookMapper extends BaseMapper {
    17. List queryUserRole(Map map);
    18. }

    MvcBookService.java

     

    1. package com.maomao.springbootmp.book.service;
    2. import com.maomao.springbootmp.book.model.MvcBook;
    3. import com.baomidou.mybatisplus.extension.service.IService;
    4. import java.util.List;
    5. import java.util.Map;
    6. /**
    7. *

    8. * 服务类
    9. *

    10. *
    11. * @author maomao
    12. * @since 2022-12-02
    13. */
    14. public interface MvcBookService extends IService {
    15. List queryUserRole(Map map);
    16. }

    MvcBookServiceImpl.java

    1. package com.maomao.springbootmp.book.service.impl;
    2. import com.maomao.springbootmp.book.model.MvcBook;
    3. import com.maomao.springbootmp.book.mapper.MvcBookMapper;
    4. import com.maomao.springbootmp.book.service.MvcBookService;
    5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Service;
    8. import java.util.List;
    9. import java.util.Map;
    10. /**
    11. *

    12. * 服务实现类
    13. *

    14. *
    15. * @author maomao
    16. * @since 2022-12-02
    17. */
    18. @Service
    19. public class MvcBookServiceImpl extends ServiceImpl implements MvcBookService {
    20. @Autowired
    21. private MvcBookMapper bookMapper;
    22. @Override
    23. public List queryUserRole(Map map) {
    24. return bookMapper.queryUserRole(map);
    25. }
    26. }

    MvcBookController.java

    1. //多表联查 ,用户姓名对应角色的功能,论证mybatis是一样可以使用mybatis功能
    2. @GetMapping("/queryUserRole")
    3. public List queryUserRole(String uname){
    4. // 前端传了一个zs
    5. Map map = new HashMap();
    6. map.put("username",uname);
    7. return bookService.queryUserRole(map);
    8. }

    用Eolink进行测试

     

  • 相关阅读:
    【paddle】自带模型参数量和计算量统计
    python自动化之BeautifulReport显示异常的解决方案
    SpringCloud Alibaba【一】简单介绍
    Numpy文本读写:loadtxt,savetxt,genfromtxt
    Java抽象类快速入门
    使用Pandas进行时间重采样,充分挖掘数据价值
    Windows版Ros环境的搭建以及Rviz显示激光点云信息
    @weakify 与 @strongify 实现原理
    Open3D (C++) 泊松盘采样
    实现一个自己的脚手架教程
  • 原文地址:https://blog.csdn.net/m12120426/article/details/128018259