本文整理自网络,侵删。
Mybatis 模糊查询和动态sql语句
模糊查询
对数据库最常用的操作就是查询了,但是如何使用Mybatis进行模糊查询呢?下面先看一个简单的模糊查询
<select id="select01" resultMap="BasicResultMap"> SELECT * FROM oa_employee WHERE emp_name LIKE #{asd} </select>
这是一条伪模糊查询, 因为没有实现真正的模糊 “%”。参数为字符串,所以#{}中内容不被限制。但是应该如何插入 % 字符呢。 我们首先想到的是传递字符串参数时将%插入到字符串中 “张%”,但是这种方法操作略微繁琐了一些。 下面提供了使用sql方法的策略
<select id="select01" resultMap="BasicResultMap"> SELECT * FROM oa_employee WHERE emp_name LIKE CONCAT( #{asd} ,'%') </select>
另外一种不推荐的写法给大家
<select id="select01" resultMap="BasicResultMap"> SELECT * FROM oa_employee WHERE emp_name LIKE '${emp_name}%' </select>
#{} 是采用预编译的写法,也就是JDBC中的PerpareStatement,这种写法可以防止sql注入,但${}这种写法是不采用预编译,其中的参数写成类中的属性或者map的key值或者为接口中注解的参数名。
mybatis 提供了bind 标签。下面举个例子
<select id="select01" resultMap="BasicResultMap"> <bind name="emp_name" value="'%'+ _parameter.getEmp_name() +'%'"/> SELECT * FROM oa_employee WHERE emp_name LIKE #{emp_name} </select>
他是在#{}表达式自动填入value值,值得注意的是“_parameter.getEmp_name()
” 调用的方法是对象中作为查询参数的属性的get方法
多条件查询
多种条件查询的要点是判断查询条件是否为空,拼接sql语句。在mybatis中提供了if标签和where 标签。 下面来介绍两种标签的用法。
if标签
<select id="select01" resultMap="BasicResultMap"> SELECT * FROM oa_employee WHERE 1=1 <if test="emp_name != null and emp_name != ''"> and emp_name = #{emp_name } </if> <if test="emp_sex != null and emp_sex != ''"> and sex = #{emp_sex} </if> </select>
mybatis 中的if标签有些类似于EL表达式的使用,test中可以直接写入类中的属性或者key值。
where标签
<select id="select01" resultMap="BasicResultMap"> SELECT * FROM oa_employee <where> <if test="emp_name != null and emp_name != ''"> and emp_name = #{emp_name } </if> <if test="emp_sex != null and emp_sex != ''"> and sex = #{emp_sex} </if> </where> </select>
这里的where标签 替换了前一段代码的 where 1=1 。 mybatis中的where 标签会判断标签内是否有内容, 如果有内容就自动生成where 并把 where 后面的第一个and +一个空格,or+一个空格 去掉。
相关阅读 >>
sql server存储过程邮件以格式形式发送的方法(代码示例)
更多相关阅读请进入《sql》频道 >>
数据库系统概念 第6版
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。