【mybatis】03-Mapper文件

 
一、select 
<select id="selectPerson" parameterType="int" resultType="hashmap">
  SELECT * FROM PERSON WHERE ID = #{id}
</select>

说明: #{id}告诉mybatis创建PreparedStatement参数     vs     ORDER BY   ${columnName}: 不转义

select支持的参数说明,具体参考 https://mybatis.org/mybatis-3/zh/sqlmap-xml.html

   

二、insert, update 和 delete
 
支持主键自动生成的配置
复制代码
<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
  insert into Author (username,password,email,bio)
  values (#{username},#{password},#{email},#{bio})
</insert>
 
<update
  id="updateAuthor"
  parameterType="domain.blog.Author"
  flushCache="true"
  statementType="PREPARED"
  timeout="20">

<delete
  id="deleteAuthor"
  parameterType="domain.blog.Author"
  flushCache="true"
  statementType="PREPARED"
  timeout="20">
复制代码

执行效果:

<mapper namespace="com.test.mapper.UserMapper">

    <insert id="save" useGeneratedKeys="true" keyProperty="user_id">
        insert into t_user (user_name, password, user_type, locked, credit, last_visit, last_ip)
        values ( #{user_name}, #{password}, #{user_type}, #{locked}, #{credit}, #{last_visit}, #{last_ip})
    </insert>
</mapper>

测试代码

User user = User.builder().user_name("aaa").password("123456").user_type(1).credit(100).last_ip("11.11.11.11").build();
userMapper.save(user);

  


三、sql
  定义可重用的 SQL 代码片段,以便在其它语句中使用
 

四、ResultMap
1)基本使用: 
复制代码
<!-- mybatis-config.xml 中,别名 -->
<typeAlias type="com.someapp.model.User" alias="User"/>

<!-- 解决列名不匹配 -->
<resultMap id="userResultMap" type="User">
  <id property="id" column="user_id" />
  <result property="username" column="user_name"/>
  <result property="password" column="hashed_password"/>
</resultMap>

<select id="selectUsers" resultMap="userResultMap">
  select user_id, user_name, hashed_password
  from some_table
  where id = #{id}
</select>
复制代码

 


 

动态SQL

参考:https://mybatis.org/mybatis-3/zh/dynamic-sql.html

通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句

一、if:根据条件作为 where 子句的一部分

复制代码
如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;
如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果
<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>
复制代码

二、choose、when、otherwise:我们不想使用所有的条件,而只是想从多个条件中选择一个使用。类似switch功能

复制代码
传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>
复制代码

三、trim、where、set:

复制代码
存在的问题:如果没有匹配条件或匹配第2个if( where and title like 此时存在语法问题)
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE
  <if test="state != null">
    state = #{state}
  </if>
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>
复制代码

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

复制代码
<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  <where>
    <if test="state != null">
         state = #{state}
    </if>
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>
复制代码

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

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

样例:
<insert id="saveCatalogInfo" parameterType="com.model.ApiInfo">
  INSERT INTO <include refid="tableName_Catalog" />
<trim prefix="(" suffix=")" suffixOverrides=",">
  id,
  <if test="name != null">apiName,</if>
  <if test="typicalScenarios != null">typicalScenarios,</if>
  <if test="interfaceFunction != null">interfaceFunction,</if>
  <if test="interfaceConstraint != null">interfaceConstraint,</if>
  <if test="requestExamples != null">requestExamples,</if>
  <if test="responseExamples != null">responseExamples,</if>
  <if test="tenant != null">tenant,</if>
  <if test="createTime != null">createTime,</if>
  <if test="updateTime != null">updateTime,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
  #{catalogId,jdbcType=VARCHAR},
  <if test="name != null">#{name,jdbcType=VARCHAR},</if>
  <if test="typicalScenarios != null">#{typicalScenarios,jdbcType=VARCHAR},</if>
  <if test="interfaceFunction != null">#{interfaceFunction,jdbcType=VARCHAR},</if>
  <if test="interfaceConstraint != null">#{interfaceConstraint,jdbcType=VARCHAR},</if>
  <if test="requestExamples != null">#{requestExamples,jdbcType=BLOB},</if>
  <if test="responseExamples != null">#{responseExamples,jdbcType=BLOB},</if>
  <if test="tenant != null">#{tenant,jdbcType=VARCHAR},</if>
  <if test="createTime != null">#{createTime,jdbcType=VARCHAR},</if>
  <if test="updateTime != null">#{updateTime,jdbcType=VARCHAR},</if>
</trim>
</insert>
复制代码

set:用于动态更新语句的类似解决方案叫做 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>
复制代码

四、foreach

对集合进行遍历(尤其是在构建 IN 条件语句的时候)

你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach

  • 当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。
  • 当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
复制代码
<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>
复制代码

 

posted @   飞翔在天  阅读(132)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示