MyBatis中的#{}和${}区别、ResultMap使用、MyBatis常用注解方式、MyBatis动态SQL

#{}和${}区别:

#{}:是占位符,采用预编译的方式sql中传值,防止sql注入,如果我们往sql中列值传递一般使用

#{}。

${}:采用字符串拼接的方式直接拼接到sql语句中,一般不用于sql列值传递,用于动态传递列名

列如:使用列名进行排序,order by ${列名},根据动态传递的列名进行排序

查询列 select {列名1},{列名2}...根据动态传递的列名进行查询

底层实现不同:

#{}:预编译的方式 ,防止sql注入,更加安全

${}:字符串直接拼接

使用场景不同

#{} :适合列值传递

${}:适合动态列名传递

特殊处理定义 ResultMap(多表关联处理结果集)

俩个元素 collection 、association

collection:关联元素处理一对多关联

例如专业与学生是一对多,专业一方配置学生集合

复制代码
public class Major {
    private int id;//专业
    private String name;//专业名称
    private List<Student> students;//专业下学生集合
}

在学生多方配置专业一方

复制代码
public class Student {
    private int id;
    private int num;
    private String name;
    private String gender;
    private Major major;//建议在学生表中关联专业,将专业信息封装到专业对象中
}

使用ResultMap组装查询结果

复制代码
<!--

专业关联学生
一对多
查询到的多个学生放到一个集合当中-->
<resultMap id="majorMap" type="Major">
    <id column="id" property="id"></id>
    <result column="name" property="name"></result>
    <collection property="students" javaType="list" ofType="Student">
        <result column="num" property="num"></result>
        <result column="sname" property="name"></result>
    </collection>
    </resultMap>
    <select id="findMajorById" resultMap="majorMap">
        select
        m.id,
        m.name,
        s.num,
        s.name sname
        from major m inner join student s on m.id=s.majorid where m.id=#{id}
    </select>

代码还有一种写法,这种写法适合分页场景,

复制代码
<!-- 分页场景-->
    <resultMap id="majorMap1" type="Major">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <collection property="students" javaType="list" select="findStudents" column="id"></collection>
    </resultMap>
    <select id="findMajors1" resultMap="majorMap1">
        select id,name from major
    </select>
    <select id="findStudents" resultType="Student">
        select num,name from student where majorid=#{id}
    </select>

association:多表关联,嵌套查询,将一个多表关联查询拆分为多次查询,先查询主表数据,然后查询关联表数据

例如查询学生的专业,学生表关联专业,学生表是主表,专业表是关联表

学生类属性定义

复制代码
 private int id;
 private int num;
 private String name;
 private String gender;
//private String mname;学生表中重新定义专业表中已经定义的,发送冗余
 //private int id;
 private Major major;//建议在学生表中关联专业,将专业信息封装到专业对象中

专业类属性定义

复制代码
private int id;//专业
private String name;//专业名称
复制代码
<resultMap id="studentMap1" type="Student">
    <id column="id" property="id"></id>
    <result column="num" property="num"></result>
    <result column="name" property="name"></result>
    <result column="gender" property="gender"></result>

    <association property="major"  javaType="Major" select="findMajorByid" column="majorid"></association>
</resultMap>
<select id="findStudent1" resultMap="studentMap1">
     select id,num,name,gender,majorid from student  where id=#{id}
</select>
<select id="findMajorByid" resultType="Major">
    select name from major where id=#{majorid}
</select>

代码还有一种写法 俩次查询写成一次查询

复制代码
     <!--关联查询-->
    <resultMap id="studentMap" type="student">
        <id column="id" property="id"></id>
        <result column="num" property="num"></result>
        <result column="name" property="name"></result>
        <result column="gender" property="gender"></result>
        <association property="major" javaType="major">
            <result column="mname" property="name"></result>
        </association>
    </resultMap>
    <select id="findStudent"  parameterType="int" resultMap="studentMap">
        select
s.id,
s.num,
s.name,
s.gender,
m.name mname
from student s inner join major m on s.majorid=m.id where s.id=#{id}
    </select>

注解方式

@select:插入sql,与xml select sql语法一样

复制代码
@Select("select id name from major")

@insert:插入sql,与xml insert sql语法一样

@update:插入sql,与xml update sql语法一样

@delete:插入sql,与xml delete sql语法一样

使用注解方式使用sql语句是,这种只适用于一些简单的sql语句,复杂的sql在xml映射文件中写会方便一些。

MyBatis动态SQL

动态sql是mybatis的强大特性之一,mybatis中实现动态sql的元素主要有if 、choose when otherwise、trim、set、where、foreach。

**if元素:**if标签可以对传入的条件进行判断

复制代码
<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>

如果if中条件不成立,就会查询满足state = 'ACTIVE'的数据,如果传入了 "title" 参数,那么就会对 "title" 一列进行模糊查找并返回对应的 BLOG 结果

choose元素:不使用所有条件,而是在多个条件中使用一个或是几个

复制代码
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>/*可以有多个when 但不能没有when*/
    <otherwise>
      AND featured = 1
    </otherwise>/*只能有一个otherwise 或者是没有*/
  </choose>
</select>

where、set、trim元素: where 元素只会在子元素返回任何内容的情况下才插入 "WHERE" 子句。而且,若子句的开头为 "AND" 或 "OR",where 元素也会将它们去除。

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:

复制代码
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>

prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。

用于动态更新语句的类似解决方案叫做 setset 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:

复制代码
<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

或者,你可以通过使用trim元素来达到同样的效果:

复制代码
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>

foreach元素: 主要用在构建 in 条件中,它可以在 SQL 语句中进行迭代一个集合。foreach
元素的属性主要有 item,index,collection,open,separator,close。
item 表示集合中每一个元素进行迭代时的别名,index 指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open 表示该语句以什么开始,
separator 表示在每次进行迭代之间以什么符号作为分隔符,close 表示以什 么结束,
在使用 foreach 的时候最关键的也是最容易出错的就是 collection 属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的。
-- 如果传入的是单参数且参数类型是一个 List 的时候,collection 属 性值为 list
-- 如果传入的是单参数且参数类型是一个 array 数组的时候, collection 的属性值为array

示例:

1、批量删除

复制代码
<delete id="deleteTeacher">
    delete  from teacher where id in
    <foreach item="id" collection="array" open="(" separator="," close=")">
        #{id}
    </foreach>/* 循环    批量删除  */
</delete>

2、循环查询

复制代码
<select id="findTeacher" resultType="com.ffyc.mybatispro.model.Teacher">
    select
     <foreach item="col" collection="list" separator=",">
         ${col}
     </foreach>
     from teacher
</select>

mybatis中文官网:mybatis -- MyBatis 3 | 简介https://mybatis.org/mybatis-3/zh_CN/index.html

相关推荐
惜.己4 小时前
MyBatis中一对多关系的两种处理方法
java·开发语言·后端·sql·mysql·mybatis·idea
终末圆4 小时前
MyBatis动态SQL中的`if`标签使用【后端 19】
java·数据结构·数据库·sql·算法·spring·mybatis
飞翔的佩奇6 小时前
Java项目: 基于SpringBoot+mybatis+maven医院管理系统(含源码+数据库+任务书+开题报告+毕业论文)
java·数据库·spring boot·毕业设计·maven·mybatis·医院管理系统
这孩子叫逆7 小时前
35. MyBatis中的缓存失效机制是如何工作的?
java·spring·mybatis
ChinaRainbowSea9 小时前
十八,Spring Boot 整合 MyBatis-Plus 的详细配置
java·数据库·spring boot·spring·mybatis·web
飞翔的佩奇19 小时前
Java项目: 基于SpringBoot+mybatis+maven课程答疑系统(含源码+数据库+毕业论文)
java·数据库·spring boot·毕业设计·maven·mybatis·课程答疑
OceanSky620 小时前
Mybatis中sql数组为空判断
数据库·sql·mybatis·数组判空
M00SE21 小时前
解决mybatis plus 中 FastjsonTypeHandler无法正确反序列化List类型的问题
mybatis
这孩子叫逆1 天前
25. MyBatis中的RowBounds是什么?如何实现内存分页?
数据库·mybatis
胡耀超1 天前
MyBatis-Plus插入优化:降低IO操作的策略与实践
sql·spring·mybatis