直接传参法
直接传参法,就是将要查询的关键字keyword,在代码中拼接好要查询的格式,如%keyword%,然后直接作为参数传入mapper.xml的映射文件中。
public void selectBykeyWord(String keyword) {String id = "%" + keyword + "%";String roleType = "%" + keyword + "%";String roleName = "%" + keyword + "%";userDao.selectBykeyWord(id,roleName,roleType);}
在Dao层指定各个参数的别名
List<RoleEntity> selectBykeyWord(@Param("id") String id,@Param("roleName") String roleName,@Param("roleType") String roleType);
<select id="selectBykeyWord" parameterType="string" resultType="com.why.mybatis.entity.RoleEntity">SELECT*FROMt_roleWHERErole_name LIKE #{roleName}OR id LIKE #{id}OR role_type LIKE #{roleType}</select>
执行出来的SQL语句
SELECT*FROMt_roleWHERErole_name LIKE '%why%'OR id LIKE '%why%'OR role_type LIKE '%why%';
CONCAT()函数
MySQL的 CONCAT()函数用于将多个字符串连接成一个字符串,是最重要的mysql函数之一。
CONCAT(str1,str2,...)
List<RoleEntity> selectBykeyWord(@Param("keyword") String keyword);
<select id="selectBykeyWord" parameterType="string" resultType="com.why.mybatis.entity.RoleEntity">SELECT*FROMt_roleWHERErole_name LIKE CONCAT('%',#{keyword},'%')ORid LIKE CONCAT('%',#{keyword},'%')ORrole_type LIKE CONCAT('%',#{keyword},'%')</select>
Mybatis的bind
List<RoleEntity> selectBykeyWord(@Param("keyword") String keyword);
<select id="selectBykeyWord" parameterType="string" resultType="com.why.mybatis.entity.RoleEntity"><bind name="pattern" value="'%' + keyword + '%'" />SELECT*FROMt_roleWHERErole_name LIKE #{pattern}ORid LIKE #{pattern}ORrole_type like #{pattern}</select>