Mybatis中一些sql语句问题

Mybatis模糊查询MySQL中记录的的常用三种方法

  • 直接使用 % 拼接字符串,如 ‘%’#{name}’%’ 或 “%”#{name}”%”,单引号或双引号都可以。
  • 使用concat(str1,str2)函数拼接
  • 使用mybatis的bind标签
    //模糊查询的常用的3种方式:
    <select id="getUsersByFuzzyQuery" parameterType="User" resultType="User">
        select <include refid="columns"/> from users
        <where>
            // 方法一: 直接使用 % 拼接字符串
            // 注意:此处不能写成  "%#{name}%" ,#{name}就成了字符串的一部分,
            // 会发生这样一个异常: The error occurred while setting parameters,
            // 应该写成: "%"#{name}"%",即#{name}是一个整体,前后加上%
            <if test="name != null">
                name like "%"#{name}"%"
            </if>
            // 方法二: 使用concat(str1,str2)函数将两个参数连接
            <if test="phone != null">
                and phone like concat(concat("%",#{phone}),"%")
            </if>
            // 方法三: 使用 bind 标签,对字符串进行绑定,然后对绑定后的字符串使用 like 关键字进行模糊查询
            <if test="email != null">
                <bind name="pattern" value="'%'+email+'%'"/>
                and email like #{pattern}
            </if>
        </where>
    </select>

Mybatis中大于小于的sql语句查询

原符号       <        <=      >       >=       &        '        "
替换符号    &lt;    &lt;=   &gt;    &gt;=   &amp;   &apos;  &quot;
  <select id="downloadTestDrives" parameterType="" resultType="">
      SELECT * FROM user
      WHERE 1=1
      <if test="endTimeStr != '' and startTimeStr != ''" >
          AND created_time &gt;= CONCAT(#{startTimeStr}) AND created_time &lt;= CONCAT(#{endTimeStr})
      </if>
  </select>

Mybatis中参数为list的sql语句查询

//判断list是否为空
<if test="list != null and list.size() > 0" >
  WHERE fd.flaw_id in
  //参数传入为 List<int> list
  <foreach collection="list" index="index" item="item" open="("
           separator="," close=")">
    #{item}
  </foreach>
</if>

Mybatis中返回参数,一个对象中的list集合

public class Demo2{
    private Integer id;

    private List<Demo> task;
}
public class Demo{
    private Integer id;
    private String name;
}
//返回对象
<resultMap id="ResultMapWorkOrder" type="com.work.power.model.Demo2">
    <id column="id" property="id" jdbcType="INTEGER" />
</resultMap>
//对象中的list
<resultMap id="ResultMap" type="com.work.power.model.Demo2" extends="ResultMapWorkOrder" >
    <collection property="task" ofType="com.work.power.model.Demo" >
        <result column="id" property="id"/>
        <result column="name" property="name"/>
    </collection>
</resultMap>

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. Mybatis模糊查询MySQL中记录的的常用三种方法
  2. 2. Mybatis中大于小于的sql语句查询
  3. 3. Mybatis中参数为list的sql语句查询
  4. 4. Mybatis中返回参数,一个对象中的list集合
本站总访问量: , 本页阅读量: