SpringBoot:ssm和springboot整合

目录

一、整合Mybatis

因为要使用逆向生成代码

pom.xml

generatorConfig.xml

application.yml

测试

BookController 

SpringbootmybatisApplication 

jdbc.properties

二、整合mybatisplus

简介

application.yml

MPGenerator 

 SpringbootmpApplication 

 三、使用mybatisplus完成多表联查功能

MvcBookMapper.xml

 MvcBookService 

 MvcBookServiceImpl 

 MvcBookMapper 

MvcBookController

一、整合Mybatis

 新建一个springboot的模块 在勾选组件时

 创建模块成功之后 

降低MySQL的版本

 

 

 账户密码

application.yml

mybatis:
    mapper-locations: classpath:mappers/*xml
    type-aliases-package: com.cdl.springbootmybatis.mybatis.entity
server:
    port: 8080
spring:
    application:
        name: springbootmybatis
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        name: defaultDataSource
        password: 123456
        url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8
        username: root

因为要使用逆向生成代码

pom.xml

<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>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mysql?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="E:\\cdl_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.cdl.springbootmybatis.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.cdl.springbootmybatis.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.cdl.springbootmybatis.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">-->
        <!--&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;-->
        <!--&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;-->
        <!--&lt;!&ndash; 指定列的java数据类型 &ndash;&gt;-->
        <!--&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;-->
        <!--</table>-->

        <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.cdl.springbootmybatis.mybatis.entity
server:
    port: 8080
spring:
    application:
        name: springbootmybatis
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        name: defaultDataSource
        password: 123456
        url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8
        username: root

 因为是一个新的工作区间(从没有运行过maven的)一定要配置maven逆向生成的命令

 完成该配置之后 再去运行逆向生成

 运行成功

 让生成出来的mapper.xml

com.cdl.springbootmybatis.model.Book中的com.cdl.springbootmybatis.model
<?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.cdl.springbootmybatis.mapper.BookMapper" >
  <resultMap id="BaseResultMap" type="com.cdl.springbootmybatis.model.Book" >
    <constructor >
      <idArg column="bid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="bname" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    bid, bname, price
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from t_mvc_book
    where bid = #{bid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from t_mvc_book
    where bid = #{bid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.cdl.springbootmybatis.model.Book" >
    insert into t_mvc_book (bid, bname, price
      )
    values (#{bid,jdbcType=INTEGER}, #{bname,jdbcType=VARCHAR}, #{price,jdbcType=REAL}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.cdl.springbootmybatis.model.Book" >
    insert into t_mvc_book
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="bid != null" >
        bid,
      </if>
      <if test="bname != null" >
        bname,
      </if>
      <if test="price != null" >
        price,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="bid != null" >
        #{bid,jdbcType=INTEGER},
      </if>
      <if test="bname != null" >
        #{bname,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        #{price,jdbcType=REAL},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.cdl.springbootmybatis.model.Book" >
    update t_mvc_book
    <set >
      <if test="bname != null" >
        bname = #{bname,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        price = #{price,jdbcType=REAL},
      </if>
    </set>
    where bid = #{bid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.cdl.springbootmybatis.model.Book" >
    update t_mvc_book
    set bname = #{bname,jdbcType=VARCHAR},
      price = #{price,jdbcType=REAL}
    where bid = #{bid,jdbcType=INTEGER}
  </update>
</mapper>

和 application.yml 对应

application.yml

mybatis:
    mapper-locations: classpath:mappers/**/*.xml
    type-aliases-package: com.cdl.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/mysql?useUnicode=true&characterEncoding=UTF-8
        username: root

此时mapper.xml中的com.cdl.springbootmybatis.model.Book可以改为Book

测试

写一个controller 

BookController 

package com.cdl.springbootmybatis.web;

import com.cdl.springbootmybatis.mapper.BookMapper;
import com.cdl.springbootmybatis.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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;

/**
 * @author cdl
 * @site www.cdl.com
 * @create 2022-10-31 20:00
 */
@RestController
@RequestMapping("/mybatis")
public class BookController {

    @Autowired
    public BookMapper bookMapper;

    //查询
    @GetMapping("/get")
    public Book list(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);
    }


}

注意:

 开启包扫描和事务管理(在启动类加)

SpringbootmybatisApplication 

package com.cdl.springbootmybatis;

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.cdl.springbootmybatis.mapper")
//开启事务管理
@EnableTransactionManagement
@SpringBootApplication
public class SpringbootmybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootmybatisApplication.class, args);
    }

}

测试时拿不到数据 404 控制台

 解决方法:在配置文件中的连接数据库的URL后面添加 useSSL=false

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=123456

效果:

控制台

查询

 删除

 

 删除成功

 新增

 新增成功

 整合mybatis成功

二、整合mybatisplus

简介

MyBatis-Plus

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

 创建一个新模块 勾选以下组件

 导入新的pom依赖(用于mp的代码生成)
        <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>

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.cdl</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依赖:用于mp的代码生成-->
        <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>
    </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.cdl.springbootmp.SpringbootmpApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

修改配置 

application.yml

server:
    port: 8080
spring:
    application:
        name: springbootmp
    datasource:
        driver-class-name: com.mysql.jdbc.Driver
        name: defaultDataSource
        password: 123456
        url: jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=UTF-8
        username: root
mybatis-plus:
    mapper-locations: classpath:mappers/**/*.xml
    type-aliases-package: com.cdl.springbootmp.book.model

新建一个mp的包 放入代码生成的类(在官网的代码生成中修改得出来的)

MPGenerator 

package com.cdl.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")指的是工作区间  "/springbootmp"所需要生成代码的模块
        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("cdl");

        // 自定义文件命名,注意 %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/mysql?useUnicode=true&characterEncoding=UTF-8&useSSL=false");
        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.cdl.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();
    }
}

注意:记得新建一个mappers的文件夹在resources下

运行该main方法

 成功了

实现基本的增删改查 MvcBookController 

package com.cdl.springbootmp.book.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdl.springbootmp.book.model.MvcBook;
import com.cdl.springbootmp.book.service.MvcBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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 cdl
 * @since 2022-10-31
 */
@RestController
@RequestMapping("/book/mvc-book")
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语句
        QueryWrapper w = new QueryWrapper();
        w.like("bname",book.getBname());
        return bookService.list(w);
    }

    //    查询单个
    @GetMapping("/load")
    public MvcBook load(MvcBook book){
        //QueryWrapper w = new QueryWrapper();
        //w.like("bid",book.getBid());
        //return bookService.getOne(w);
        return bookService.getById(book.getBid());
    }

    //    增加
    @PutMapping("/add")
    public boolean add(MvcBook book){
        boolean save = bookService.save(book);
        return save;
    }

    //    修改
    @PostMapping("/update")
    public boolean update(MvcBook book){
        boolean save = bookService.saveOrUpdate(book);
        return save;
    }

    //    删除
    @DeleteMapping("/delete")
    public boolean delete(MvcBook book){
        boolean save = bookService.removeById(book.getBid());
        return save;
    }


}

注意:

 SpringbootmpApplication 

package com.cdl.springbootmp;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@MapperScan("com.cdl.springbootmp.book.mapper")  //扫描接口
@EnableTransactionManagement  //开启事务
@SpringBootApplication
public class SpringbootmpApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootmpApplication.class, args);
    }

}

测试:

查询

 查询带条件

 修改

 修改成功

 三、使用mybatisplus完成多表联查功能

MvcBookMapper.xml

 <!--多表联查-->
    <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>

 MvcBookService 

package com.cdl.springbootmp.book.service;

import com.cdl.springbootmp.book.model.MvcBook;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author cdl
 * @since 2022-10-31
 */
public interface MvcBookService extends IService<MvcBook> {

    //多表联查
    List<Map> queryUserRole(Map map);

}

 MvcBookServiceImpl 

package com.cdl.springbootmp.book.service.impl;

import com.cdl.springbootmp.book.model.MvcBook;
import com.cdl.springbootmp.book.mapper.MvcBookMapper;
import com.cdl.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 cdl
 * @since 2022-10-31
 */
@Service
public class MvcBookServiceImpl extends ServiceImpl<MvcBookMapper, MvcBook> implements MvcBookService {

    @Autowired
    private MvcBookMapper bookMapper;
    public List<Map> queryUserRole(Map map){
        return bookMapper.queryUserRole(map);
    }

}

 MvcBookMapper 

package com.cdl.springbootmp.book.mapper;

import com.cdl.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 cdl
 * @since 2022-10-31
 */
@Repository
public interface MvcBookMapper extends BaseMapper<MvcBook> {

    //多表联查
    List<Map> queryUserRole(Map map);

}

MvcBookController


中加这个方法

 //多表联查 用户账户对应角色的功能  论证mybatisplus一样可以使用mybatis
    @GetMapping("/userRole")
    public List<Map> userRole(String uname){
        Map map = new HashMap();
        map.put("username",uname);
        List<Map> maps = bookService.queryUserRole(map);
        return maps;
    }

测试:

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当前可以使用Spring Boot整合SSM框架。首先,你可以将SpringMyBatis整合Spring Boot中。Spring Boot会自动为你处理SpringMyBatis的配置,你只需要保留一些必要的配置即可。具体来说,你可以使用Spring Boot的starter依赖来引入SpringMyBatis的相关模块。这样,你就可以使用Spring的依赖注入和事务管理功能,以及MyBatis的ORM功能。 接下来,你可以使用Spring Boot整合Spring MVC。Spring Boot提供了一个自动配置的MVC模块,你可以直接使用它来处理HTTP请求和响应。你只需要在Controller类上添加@Controller注解,并在方法上添加@RequestMapping注解来定义请求映射。此外,你还可以使用Spring Boot的starter依赖来引入其他需要的模块,比如JSON序列化和数据校验等。 最后,你可以使用Spring Boot整合JUnit进行测试。你可以使用@SpringBootTest注解标记测试类,并指定主程序引导类。通过自动装配业务方法,你可以在测试方法中直接调用你的业务逻辑。这样,你就可以方便地进行单元测试和集成测试了。 综上所述,你可以使用Spring Boot整合SSM框架,实现快速开发和测试。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [基于SpringBootSSM整合](https://blog.csdn.net/ware00/article/details/125689235)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值