一.用xml文件的形式来操作数据库

 1.添加依赖


<!--spring整合mybatis-plus 删除mybatis的包 -->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.3</version>
</dependency>


2.创建mapper.xml文件

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_sql语句

3.在application.yml文件配置该xml文件的位置  

开启驼峰映射是数据库中的字段和实体类中属性之间的映射 例如 实体类中属性userName 和数据库中的字段user_name之间可以进行映射


#开启驼峰映射 configuration: map-underscore-to-camel-case: true


spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_spring_02

4.创建一个xxxmapper接口,里面写一个抽象方法 注解@Param("name")是老版本需要添加的,底层封装了一个map集合,键是name 而值是实参传来的数据 新版本不需要添加

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_spring boot_03

***当只需要执行简单sql语句时,可以使用注解的方式来进行操作,而不需要xxx.xml文件,注解一般有@Select("sql语句") @update("sql语句") @delete("sql语句")@insert("sql语句")等等

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_sql语句_04

5.在xx.xml文件写sql语句操作数据库

namespace属性值是xxxMapper所在的位置 id属性是xxxMapper中抽象方法的名字 #{name}是取抽象方法中的参数 resultType 是抽象方法中返回值的类型(具体来讲就是实体类,因为sql语句执行会得到一个结果,这是会映射到一个实体类,该实体类返回给调用xxxMapper方法的一个对象)  这个名字可以在配置类起一个别名 

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_spring_05

 

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_java_06

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_实体类_07

resultMap使用场景:当实体类中的属性和数据库表的字段名称不同或者不满足驼峰规则时,需要进行配置,配置规则如下

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_spring_08

****动态sql查询数据库

<?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="cn.tedu.mapper.DeptMapper">
    <!--sql标签:提取SQL片段,提高SQL片段复用性-->
    <sql id="cols">
        id,dname,loc
    </sql>
    <select id="getById" resultType="cn.tedu.pojo.Dept">
        select  
         <include refid="cols"></include>
         from dept where id=1
    </select>
    <select id="getByName" resultType="cn.tedu.pojo.Dept">
        select  * from dept
        <if test="name!=null">
            where dname=#{name}
        </if>
    </select>
   <insert id="addDept">
       insert into dept values(null,"研发","二区")
   </insert>
    <delete id="deleteDept">
       /* delete from dept where id<3*/
       /*collection表示要遍历的那种集合中的数据,是固定值:array/ist/Map*/
       delete  from dept where id in 
        <foreach collection="array" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>
</mapper>

二、用对象的方式来操作数据库

 1.在实体类标记表名和主键和属性

注解@TableField("数据库中的表名") 

@TableId(type=IdType.AUTO)标记主键和递增规则

@TableField("数据库中的字段名")若和数据库中的字段名一样可省略不写

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_sql语句_09

  2.在xxxmapper接口中继承BaseMapper<实体类> 

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_spring_10

3.就可以使用接口BaseMapper中的方法类操作数据库了

spring boot 启动 mybatis plus 卡住 springboot配置mybatis plus_spring boot_11

 *****其中QueryWrapper<实体类>是一个条件构造器,相当于sql语句中的where条件,他会自动根据传进来的参数进行拼接(里面有很多方法需要自己多写写!)