一、mybatis模糊查找的几种写法(转载):
1. sql中字符串拼接
SELECT * FROM tableName WHERE name LIKE CONCAT(CONCAT('%', #{text}), '%');
2. 使用 ${...} 代替 #{...}
SELECT * FROM tableName WHERE name LIKE '%${text}%';
3. 程序中拼接
Java
// String searchText = "%" + text + "%";
String searchText = new StringBuilder("%").append(text).append("%").toString();
parameterMap.put("text", searchText);
SqlMap.xml
SELECT * FROM tableName WHERE name LIKE #{text};
4. 大小写匹配查询
SELECT * FROM TABLENAME WHERE UPPER(SUBSYSTEM) LIKE '%' || UPPER('jz') || '%'
或者
SELECT * FROM TABLENAME WHERE LOWER(SUBSYSTEM) LIKE '%' || LOWER('jz') || '%'
在mybatis模糊查找时出现There is no getter for property named 'teacherName' in 'class java.lang.String'
错误写法:
1 <select id="findAllProjectLevelByTeacher" parameterType="String" resultType="String"> 2 SELECT DISTINCT Level FROM project WHERE TeacherName LIKE '%${teacherName}%' 3 </select>
解决方法:这种情况下,不管函数里面参数名是什么,都要改为_parameter
正确写法:
1 <select id="findAllProjectLevelByTeacher" parameterType="String" resultType="String"> 2 SELECT DISTINCT Level FROM project WHERE TeacherName LIKE '%${_parameter}%' 3 </select>
二、mybatis查询时多参数的传递方法
1、通过hashmap来传,在XML中配置好对应的parameterMap。通过属性<select>的parameterMap或者parameterType调用即可
注意:在定义函数时,参数也应该是hashmap类型的
2、XML中直接用#{1},#{2}...等方法把对应的参数传入,注意定义函数时,需用@Param("")对应把每个参数与XML中的参数名对应起来。
XML:
1 <select id="findAllProjectNameByLevel" resultType="String"> 2 SELECT DISTINCT Name FROM project WHERE TeacherName LIKE '%${teacherName}%' AND Level LIKE '%${level}%' 3 </select>
DAO:
1 List<String> findAllProjectNameByLevel(@Param("teacherName")String teacherName,@Param("level")String level);
注意:模糊查找时,只有一个参数的时候用_parameter,在模糊查找条件只有一个,即一个Like '%%',但还有其他参数时,如 select * from student where sName like '%参数1%' limit 参数2,参数3,这种情况也是和多参数传递方法一样的
三、mybatis查询语句中不能出现大于(>)和小于(<)
如果在mybatis中需要用到大于(>)和小于(<),需用转义后使用:
< <
> >
<> <>
& &
' '
" "
也可以改写一下mybatis查询代码
如,错误语句
select *from student where grade1>#{grade} and grade2<#{grade}
如果这样写,会报:The content of elements must consist of well-formed character data or markup
正确写法:
SELECT * FROM tax WHERE <![CDATA[grade1 > #{grade}]]> AND <![CDATA[grade2< #{grade}]]>