Mybatis进阶之动态SQL

1、MyBatis获取参数值的两种方式

MyBatis获取参数值的两种方式:${}#{}

${}的本质就是字符串拼接,#{}的本质就是占位符赋值

${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引

号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,

可以自动添加单引号

1.1 多种查询情况

  1. 通过一个参数查询一个实体类对象

    Admin getAdminByyym(String username);
    <!-- 1.为单个变量时  Admin getAdminByyym(String username);-->
      <select id="getAdminByyym" resultType="com.pojo.Admin">
           <!-- select * from admin where yhm = #{username}   {}里的值是任意的 -->  
           select * from admin where yhm = '${usename}' <!-- 用$必须加单引号 且里面的值只能为usename -->
      </select>

    只有一个参数的时候{}里的参数名字随便写,他都能一一对应。

  2. 通过两个及以上的参数查询一个实体类对象

          2.1 使用param1、param2.....进行赋值

  //多个参数变量获取值时
  Admin checklogin(String yhm,String mm);
<!-- 2.为多个变量时  Admin checklogin(String yhm,String mm); -->
<select id="checklogin" resultType="com.pojo.Admin">
    select * from admin where yhm = #{param1} and mm = #{param2}
</select>

使用 #{param1}指定对应的参数为第一个

    2.2 使用 @Param给参数命名
Admin checkLoginByParam(@Param("yhm") String yhm, @Param("mm") String mm);
<!-- Admin checkLoginByParam(@Param("yhm") String yhm, @Param("mm") String mm); -->
<select id="checkLoginByParam" resultType="com.pojo.Admin">
    select * from admin where yhm = #{yhm} and mm = #{mm}
</select>

#{yhm}里的参数名要跟@Param("yhm")保持一致 

        2.3  使用map封装参数(推荐使用)

 User selectUserBymap(Map<String, Object> map);
  <!--  User selectUserBymap(Map<String, Object> map); -->
  <select id="selectUserBymap" resultType="com.mybatis.pojo.User" parameterType="java.util.Map">
     select * from t_user where userName = #{userName} and userPassword = #{userPassword}
  </select>  
    Map<String, Object> map = new HashMap<>();
    map.put("userName", "czh");
    map.put("userPassword", "654321");
    
    User user =  userMapper.selectUserBymap(map);
    System.out.println(user);

这时候#{}里的变量要与JavaBean一致。

2. 其他可能用到的案例:

  1. 查个数

      //1.查询总数
      Integer getcount();
          <!-- Integer getcount(); -->
          <select id="getcount" resultType="Integer">
                 select count(*) from admin
          </select>
  2. 多个参数的添加

     //多个参数添加值时
      void insertAdminByparam(Admin admin);
           <!-- 多个变量添加时  void insertAdminByparam(Admin admin); -->
          <insert id="insertAdminByparam">
              insert into admin values(null,#{yhm},#{mm})
          </insert>
    
    
     Admin admin5 =new Admin(null, "1","12");
     adminMapper.insertAdminByparam(admin5); 

    {}里的参数要与数据库表字段一致

  3.  

    批量添加多个员工

      void inertMoreAdmin(@Param("admins") List<Admin> admins);
          <!-- void inertMoreAdmin(@Param("admins") List<Admin> admins); -->
          <insert id="inertMoreAdmin">
               insert into admin values
               <foreach collection="admins" item="admins" separator=",">
                   (null,#{admins.yhm},#{admins.mm})
               </foreach>
          </insert>
        //批量添加
        Admin admin7 = new Admin(null,"12","12");
        Admin admin8 = new Admin(null,"12333","12333");
        List<Admin> list2 = new ArrayList<>();
        list2.add(admin7);
        list2.add(admin8);
        adminMapper.inertMoreAdmin(list2);

    4. 模糊查询      '%${yhm}%'

  //模糊查询的使用
  List<User> selectUserByLike(String userName);
  <!--  List<User> selectUserByLike(); -->
  <select id="selectUserByLike" resultType="com.mybatis.pojo.User" parameterType="String" >
      select * from t_user where userName like '%${yhm}%'
  </select>

3、动态SQL

Mybatis框架的动态SQL技术是一种根据特定条件动态拼装SQL语句的功能,它存在的意义是为了

解决 拼接SQL语句字符串时的痛点问题。

3.1 if

if标签可通过test属性的表达式进行判断,若表达式的结果为true,则标签中的内容会执行;反之

标签中的内容不会执行

  <!--  List<User> userList(User user); -->
  <select id="userList" resultType="com.mybatis.javaBean.User" parameterType="com.mybatis.javaBean.User">
      select * from t_user where 1=1
      <if test="userName != '' and userName != null">
          and userName like '%${userName}%'
      </if>
      <if test="userPassword != '' and userPassword != null ">
          and userPassword = #{userPassword}
      </if>
      <if test="sex != '' and sex != null ">
          and sex = #{sex}
      </if>
  </select>
    User user2 = new User();
    user2.setUserName("李明");
    user2.setSex("男");
    List<User> usersLists = userMapper.userList(user2);
    System.out.println(usersLists);

3.2 where

where就是数据库中的where语句,它一般和if结合使用;

a>若where标签中的if条件都不满足,则where标签没有任何功能,即不会添加where关键字

b>若where标签中的if条件满足,则where标签会自动添加where关键字,并将条件最前方多余的

and去掉

注意:where标签不能去掉条件最后多余的and

  <select id="userList" resultType="com.mybatis.pojo.User" parameterType="com.mybatis.pojo.User">
      select * from t_user
     <where>
        <if test="userName != '' and userName != null">
          userName like '%${userName}%'
      </if>
      <if test="userPassword != '' and userPassword != null ">
          and userPassword = #{userPassword}
      </if>
      <if test="sex != '' and sex != null ">
          and sex = #{sex}
      </if>
     </where>
  </select>

3.3 trim

trim用于去掉或添加标签中的内容

常用属性:

prefix:在trim标签中的内容的前面添加某些内容

prefixOverrides:在trim标签中的内容的前面去掉某些内容

suffix:在trim标签中的内容的后面添加某些内容

suffixOverrides:在trim标签中的内容的后面去掉某些内容

 <select id="userList" resultType="com.mybatis.pojo.User" parameterType="com.mybatis.pojo.User">
    select * from t_user 
    <trim prefix="where" suffixOverrides="and">
      <if test="userName != '' and userName != null">
          userName like '%${userName}%' and 
      </if>
      <if test="userPassword != '' and userPassword != null ">
          userPassword = #{userPassword} and 
      </if>
      <if test="sex != '' and sex != null ">
          sex = #{sex}
      </if>
    </trim>
  </select>
​
​
 <insert id="insertSelective" parameterType="com.buyerApp.system.admin.admin.pojo.Admin">
    insert into admin
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="yhm != null">
        yhm,
      </if>
      <if test="mm != null">
        mm,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="yhm != null">
        #{yhm,jdbcType=VARCHAR},
      </if>
      <if test="mm != null">
        #{mm,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>

3.4 choose、when、otherwise

choose、when、 otherwise相当于if...else if..else

 <select id="userList" resultType="com.mybatis.pojo.User" parameterType="com.mybatis.pojo.User">
    select * from t_user
    <where>
       <choose>
          <when test="userName != '' and userName != null">
              userName = #{userName}
          </when>
          <when test="userPassword != '' and userPassword != null">
              userPassword = #{userPassword}
          </when>
          <when test="sex != '' and sex != null ">
              sex = #{sex}
          </when>
          <otherwise>
              age = 20
          </otherwise>
       </choose>
    </where>
测试
    User user2 = new User();
    user2.setUserName("李明");
    user2.setSex("男");
    List<User> usersLists = userMapper.userList(user2);
    System.out.println(usersLists);

最终结果只满足一个

DEBUG [main] - ==>  Preparing: select * from t_user WHERE userName = ? 
DEBUG [main] - ==> Parameters: 李明(String)
DEBUG [main] - <== Total: 1
[User [id=4, userName=李明, userPassword=123, sex=男, age=25]]

3.5 foreach

循环

<!--  int InsertmoreUser(@Param("userlist") List<User> list);-->
  <insert id="InsertmoreUser" >
     insert into t_user values
       <foreach collection="userlist" item="user" separator=","> 
           (null,#{user.userName},#{user.userPassword},#{user.sex},#{user.age})
        </foreach>
  </insert>
​
<!--int deleteMoreByArray(int[] eids);-->
<delete id="deleteMoreByArray">
  delete from t_emp where
  <foreach collection="eids" item="eid" separator="or">
    eid = #{eid}
  </foreach>
</delete>
​
<!--int deleteMoreByArray(int[] eids);-->
<delete id="deleteMoreByArray">
  delete from t_emp where eid in
  <foreach collection="eids" item="eid" separator="," open="(" close=")">
    #{eid}
  </foreach>
</delete>

这里的collection是指所有的数据,item指的是这所有数据要循环的单个数据。#{user.userName}其中userName要与Java Bean中的变量一致。

3.6、SQL片段

sql片段,可以记录一段公共sql片段,在使用的地方通过include标签进行引入

    <sql id="userColumns">
       userName,userPassword,sex
    </sql>
   select <include refid="userColumns"></include> from t_user

注意:没查到的默认为0 或者 null

3.7 set

用于update语句中

 <update id="updateByPrimaryKeySelective" parameterType="com.buyerApp.system.admin.admin.pojo.Admin">
    update admin
    <set>
      <if test="yhm != null">
        yhm = #{yhm,jdbcType=VARCHAR},
      </if>
      <if test="mm != null">
        mm = #{mm,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>

具体案例源代码:mybatis源代码

  • 21
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小陈编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值