MyBatis动态Sql语句讲解.doc

  1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
MyBatis动态Sql语句讲解

MyBatis动态Sql语句 MyBatis中对数据库的操作,有时要带一些条件,因此动态SQL语句非常有必要,下面就主要来讲讲几个常用的动态SQL语句的语法 MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) trim where set foreach 1、if 对属性进行判断,如果不为空则执行判断条件 [html] view plain copy select id=selectByCriteria parameterType=com.mucfc.dto.Student resultMap=BaseResultMap select * from t_student where if test=stuId != null and stuId != STU_ID = #{stuId} /if if test=stuName != null and stuName != and STU_NAME = #{stuName} /if if test=stuClass != null and stuClass != and STU_CLASS = #{stuClass} /if if test=stuSex != null and stuSex != and STU_SEX=#{stuSex} /if if test=stuAge != null and stuAge != and STU_AGE=#{stuAge} /if /select 来看看结果: 这是从web页面输入的参数 这是输出的结果 这是打印出来的Sql语句 从结果可以看出,只有在条件不为空的时候,属性才会赋值。 2、where 当where中的条件使用的if标签较多时,这样的组合可能会导致错误。我们以在1中的查询语句为例子,当输入参数stuId为空时,就会报错 然后是输出的结果: 此时SQL语句变成了select * from t_student where and STU_SEX=?这样会报错 如果上面例子,参数stuId为null,将不会进行STUDENT_NAME列的判断,则会直接导“WHERE AND”关键字多余的错误SQL。这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。 可以改成如下: [html] view plain copy select id=selectByCriteria parameterType=com.mucfc.dto.Student resultMap=BaseResultMap select * from t_student where if test=stuId != null and stuId != STU_ID = #{stuId} /if if test=stuName != null and stuName != and STU_NAME = #{stuName} /if if test=stuClass != null and stuClass != and STU_CLASS = #{stuClass} /if if test=stuSex != null and stuSex != and STU_SEX=#{stuSex} /if if test=stuAge != null and stuAge != and STU_AGE=#{stuAge} /if /where /select 再来看看,输入查询条件 然后输出结果 打印出来的SQL语句 - == Preparing: select * from t_student WHERE STU_SEX=? == Parameters: 男(String) == Total: 14 说明结果是正确的。如果它包含的标签中有返回值的话就插入一个where。此外如果标签返回的内容是以AND或OR开头

文档评论(0)

33ggoup + 关注
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档