SSM框架实战详细教程(十二)MyBatis动态语句与${}参数

        本篇文章介绍MyBatis较为常用的两个知识点,一个是动态语句,一个是${}参数。
        动态语句:
        提供where、set、if、trim、choose等标签,我们以if为例,加入我们想通过条件组合的形式查询学生数据,如单独查姓名、性别、年龄,也可以两两组合,也可以三个组合:

List<Student> searchByCondition3(Student stu);
<select id="searchByCondition3" resultType="entity.Student">
    select * from student where 1=1
    <if test="name!=null and name!=''">
       and name=#{name}
    </if>
    <if test="gender!=null and gender!=''">
        and gender=#{gender}
    </if>
    <if test="age!=null and age!=0">
        and age=#{age}
    </if>
</select>

测试类:

    Student stu = new Student();
    //stu.setName("小红");
    // stu.setGender("女");
  	stu.setAge(20);
    List<Student> list = studentDao.searchByCondition3(stu);
    for (Student s : list) {
        System.out.println(s.getName());
    }

        #{}和${}:
        #{}传参的形式,我们一直在使用,它会判断Java中的类型,如果是字符串,为注入到SQL中的变量自动添加SQL语法中所要求的单引号:’’,但是在有些场景下,它的这一特性,反而解决不了不了问题,如:

List<Student> searchLike(@Param("name") String name);
   <select id="searchLike" resultType="entity.Student">
        select * from student where name like '%#{name}%'
    </select>

        如果此时还用#{},测试时候传入“小"字符串,则会出现SQL效果如下,是不符合SQL语法的:

select * from student where name like '%''%'

        改用${}:

   <select id="searchLike" resultType="entity.Student">
        select * from student where name like '%${name}%'
    </select>

        则生成正常的SQL如下:

select * from student where name like '%小%'
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值