首页 > 数据库技术 > 详细

mybatis中的动态sql

时间:2019-06-11 22:58:00      阅读:107      评论:0      收藏:0      [点我收藏+]

mybatis的xml映射文件里写了对数据库的操作,有些sql可能很繁琐,比如有一个方法是根据姓名查找学生,有个是根据身份证id查学生。。。这样的话就很冗余。可以用if来做一定的简化

也就是如果参数中有学生的某个属性,就拼接该属性到需要查询关联的sql中去

举个栗子

<select id="queryByNameOrSex" resultType="student" parameterType="student">
  select * from student where 1=1
  <if test="sname!=null and sname!=‘‘">
    sname=#{sname}
  </if>
  <if test="ssex!=null">
    and ssex=#{ssex}
  </if>
</select>

用where 1=1是为了防止如果sname没有的话,就会where and ssex=true;语法报错。这是比较low的解决方法,当然了mybatis早就预料到了这种low方法,所以还提供了另外一个sql标签

<select id="queryByNameOrSex" resultType="student" parameterType="student">
  select * from student 

<where>
  <if test="sname!=null and sname!=‘‘">
    and sname=#{sname}
  </if>
  <if test="ssex!=null">
    and ssex=#{ssex}
  </if>

</where>
</select>

也就是where标签,然后在每个if标签里都加上and,mybatis会自动识别那个and是不需要的,哇卡卡卡有点智能哦

mybatis中的动态sql

原文:https://www.cnblogs.com/liuyongbo/p/11006434.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!