Mybatis使用

这篇博客详细介绍了Mybatis中常用的动态SQL标签,包括collection用于遍历集合的用法,foreach在delete批量删除和insert批量添加中的应用,以及if、where、trim、set、bind和choose、when、otherwise等标签的使用示例和功能解析,帮助开发者更好地理解和运用Mybatis动态SQL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

collection标签

代码

mapper

	/**
     * 查询模板卡片
     * @param companyId
     * @return List<TaxDraftTemplatePO>
     */
    List<TaxDraftTemplatePO> selectTaxDraftTemplateInfoByCompanyId (@Param("companyId") Long companyId, @Param("taxType") String taxType);
    /**
     * 查询当前模板最后修改时间
     * @param templateId
     * @return int
     */
    Date selectMAXGmtModifyByTemplateId (@Param("templateId") Long templateId);

mapper.xml

<?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.nuonuo.tax.enterprise.dao.mapper.TaxDraftTemplateManageMapper">

    <resultMap id="TaxDraftTemplateResultMap" type="com.nuonuo.tax.enterprise.dao.po.TaxDraftTemplatePO">
        <result column="id" property="id" jdbcType="BIGINT"/>
        <result column="tax_type" property="taxType" jdbcType="VARCHAR"/>
        <result column="template_code" property="templateCode" jdbcType="VARCHAR"/>
        <result column="template_name" property="templateName" jdbcType="VARCHAR"/>
        <result column="template_type" property="templateType" jdbcType="VARCHAR"/>
        <result column="nsrxz" property="nsrxz" jdbcType="VARCHAR"/>
        <result column="declare_type" property="declareType" jdbcType="VARCHAR"/>
        <result column="collection_method" property="collectionMethod" jdbcType="VARCHAR"/>
        <result column="report_type" property="reportType" jdbcType="VARCHAR"/>
        <result column="industry_type" property="industryType" jdbcType="VARCHAR"/>
        <result column="company_id" property="companyId" jdbcType="VARCHAR"/>
        <result column="source_template_id" property="sourceTemplateId" jdbcType="INTEGER"/>
        <result column="gmt_create" property="gmtCreate" jdbcType="TIMESTAMP"/>
        <result column="operator" property="operator" jdbcType="VARCHAR"/>
        <collection property="gmtModify" jdbcType="TIMESTAMP" column="{templateId=id}" select="selectMAXGmtModifyByTemplateId"/>
    </resultMap>

    <resultMap id="TemplateCompanyRelResultMap" type="com.nuonuo.tax.enterprise.dao.po.TemplateCompanyRelPO">
        <result column="id" property="id" jdbcType="BIGINT"/>
        <result column="template_id" property="templateId" jdbcType="BIGINT"/>
        <result column="company_id" property="companyId" jdbcType="BIGINT"/>
        <result column="gmt_create" property="gmtCreate" jdbcType="TIMESTAMP"/>
        <result column="gmt_modify" property="gmtModify" jdbcType="TIMESTAMP"/>
    </resultMap>
     <sql id="Base_Column_List">
        id, tax_type, template_code, template_name, template_type, nsrxz,
        declare_type, collection_method, report_type, industry_type,
        company_id, source_template_id, gmt_create, operator
    </sql>
    <select id="selectTaxDraftTemplateInfoByCompanyId" resultMap="TaxDraftTemplateResultMap">
        select
            <include refid="Base_Column_List"/>
        from
            tax_draft_template tdt
        where tdt.company_id = #{companyId}
        and tdt.tax_type = #{taxType}
    </select>
    <!--declare_draft_template_company_rel-->
    <select id="selectMAXGmtModifyByTemplateId" parameterType="java.util.HashMap" resultType="Date">
        select MAX(gmt_modify) gmt_modify
        from declare_draft_template_company_rel tcr
        where tcr.template_id = #{templateId,jdbcType=VARCHAR}
    </select>
</mapper>

foreach标签

delete批量删除

代码

mapper
/**
     * 删除模板与组织分配关系
     * @param templateId
     * @param companyIds
     * @return int
     */
    int deleteRelByTemplateIdCompanyId(@Param("templateId")Long templateId, @Param("companyIds") List<Long> companyIds);

mapper.xml
    <!--  通过模板id和companyId删除对应的模板组织关系  -->
    <delete id="deleteRelByTemplateIdCompanyId">
        DELETE FROM declare_draft_template_company_rel
        WHERE template_id = #{templateId}
        AND company_id in
        <foreach collection="companyIds" item="companyId" index="index" open="(" separator="," close=")">
            #{companyId}
        </foreach>
    </delete>

insert批量添加

代码

mapper
    /**
     * 保存模板公司关系
     * @param companyInfoS
     * @return
     */
    int insertIntoTemplateCompanyRel(@Param("companyInfoS") List<TemplateCompanyRelPO> companyInfoS);
mapper.xml
 <!--  useGeneratedKeys="true" 插入成功后返回该数据的主键 注意没有 open="(" 和 close=")" -->
    <insert id="insertIntoTemplateCompanyRel" parameterType="com.nuonuo.tax.enterprise.dao.po.TemplateCompanyRelPO"  useGeneratedKeys="false">
        insert into declare_draft_template_company_rel
        (template_id, company_id)
        values
        <foreach collection="companyInfoS" item="companyInfo" index="index" separator=",">
            (
                #{companyInfo.templateId},
                #{companyInfo.companyId}
            )
        </foreach>
    </insert>

select

动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。

代码

mapper.xml
<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>

遍历数组中的每个元素, 与ID进行匹配让然后进行条件查询
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。
它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。
这个元素也不会错误地添加多余的分隔符。
提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

if 标签

根据条件是否执行where的某一子句, 因为where不是形式, 所以必须有一个if条件成立, 不然会报错

代码

mapper.xml

<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
  <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的增强, 如果where中的if都不成立, 则相当于没有where条件, 并不会报错

代码

mapper.xml

<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 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
可以通过自定义 trim 元素来定制 where 元素的功能。如上.
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。

代码

mapper.xml

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...</trim>

<trim prefix="" suffix="" suffixOverrides="" prefixOverrides=""></trim>

prefix:
表示在trim包裹的SQL语句前面添加的指定内容。
suffix:
表示在trim包裹的SQL末尾添加指定内容
prefixOverrides:
表示去掉(覆盖)trim包裹的SQL的指定首部内容
suffixOverrides:
表示去掉(覆盖)trim包裹的SQL的指定尾部内容

set 标签

代码

mapper.xml

<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 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
set 元素等价的自定义 trim 元素

<trim prefix="SET" suffixOverrides=",">
  ...</trim>

bind 标签

bind 元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。

代码

mapper.xml

<select id="selectBlogsLike" resultType="Blog">
  <bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
  SELECT * FROM BLOG
  WHERE title LIKE #{pattern}
</select>

意思就是说将value拼接后的结果给name的值, 这样就可以利用bind标签实现模糊查询, 并且这种方式适用于多种数据库, 例如:

<if test="responsiblePersonNumber != null and responsiblePersonNumber != '' ">
    <bind name="responsiblePerson" value="'%'+responsiblePersonNumber+'%'"/>
    and jsxx.JGH like #{responsiblePerson} or jsxx.XM like #{responsiblePerson}
</if>
当然上述语句也可以用concat实现(mysql形式写法)
<if test="responsiblePersonNumber != null and responsiblePersonNumber != '' ">
       and jsxx.JGH like concat('%',#{responsiblePersonNumber},'%') or jsxx.XM like concat('%',#{responsiblePersonNumber},'%')
</if>
因为oracle数据库中concat方法只能传两个参数所以, 换成Oracle数据库就会报错, 要想用concat实现模糊查询, 必须使用concat嵌套, 例如:
<if test="responsiblePersonNumber != null and responsiblePersonNumber != '' ">
    and jsxx.JGH like concat(concat('%',#{responsiblePersonNumber}),'%') or jsxx.XM like concat(concat('%',#{responsiblePersonNumber}),'%')
</if>

所以, 我们最好使用标签进行模糊查询

choose、when、otherwise 标签

代码

mapper.xml

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

从多个条件中选择一个使用。相当于java中的switch语句, otherwise相当于switch的default, when相当于case, choose相当于switch

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值