【学习笔记】Mybatis 【动态SQL】

动态sql-if标签与where标签

(1)if标签
if标签:可以判断传入的参数是否为空,如果不为空则拼接sql

     <if test="id!=null and id!=''">
       and id = #{id}
    </if>

(2)where标签

  • where标签可以自动检测拼接条件是否全部不成立,等同于where 1=1 不会造成语法错误
select * from table where //不会出现

where 1=1的用处 主要用来构件动态SQL

String sql = “select a,b from table_a where 1=1 “;
if(!b.equals(””))
sql += “and b=’”+b+"’"; 当用户选择了b ( 假如b值为qwe ) 结果就是:String sql = ''select a,b from table_a where 1=1 and b= ‘qwe’;

但是当用户没有选择b 那b就是一个空值

结果就是:String sql =’‘select a,b from table_a where 1=1’’; ,运行也不会出错,相当于没有限制b这个条件。

但是如果没有1=1的条件,则l String sql =’‘select a,b from table_a where’’ ; 这样就会报错。

  • 同时还可以自动检测第一个拼接条件前是否有and,有and会自动消掉,不会造成
select * from table where and id=

(3)foreach标签
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。
例如:select * from table where id in(1,2,3)

foreach元素的属性主要有 item,index,collection,open,separator,close。

  • item表示集合中每一个元素进行迭代时的别名,
  • index指 定一个名字,用于表示在迭代过程中,每次迭代到的位置,
  • open表示该语句以什么开始,
  • separator表示在每次进行迭代之间以什么符号作为分隔 符,
  • close表示以什么结束。
    在使用foreach的时候最关键的也是最容易出错的就是collection属性

该属性是必须指定的,其中collection的属性值与接口的参数名没有任何关系
在这里插入图片描述
如果希望使用别名需要用@param指定
在这里插入图片描述
使用示例:
配置文件

<select id="selectMoreInfo" resultType="com.glc.bean.user">
    select * from `user`
    <where>
        <if test="id!=null and id!=''">
           and id = #{id}
        </if>
        <if test="username!=null and username!=''">
           and username like #{username}
        </if>
        <if test="birthday!=null and birthday!=''">
            and birthday = #{birthday}
        </if>
        <if test="sex!=null and sex!=''">
            and sex = #{sex}
        </if>
        <if test="address!=null and address!=''">
            and  address = #{address}
        </if>
    </where>
</select>

接口:

public interface UserDao {
    public List<user> selectMoreInfo(user user) ;
}

测试类:

@org.junit.Test
public void TestSelectMoreInfo(){
    //获得session对象

    SqlSession sqlsessio = MySessionUtils.getSession();
    UserDao mapper = sqlsessio.getMapper(UserDao.class);
    user user = new user();
    user.setUsername("%小%");
    user.setAddress("广州");
    List<user> users =  mapper.selectMoreInfo(user);
    System.out.println(users);
    //调用getMapper
    sqlsessio.commit();
    sqlsessio.close();
    //查询订单
    //关闭连接
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值