第一种
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);
mapper.xml中
<select id="selectBykeyWord" parameterType="string" resultType="com.why.mybatis.entity.RoleEntity">
SELECT * FROM t_role WHERE role_name LIKE #{roleName} OR id LIKE #{id} OR role_type LIKE #{roleType} </select> 执行出来的SQL语句:SELECT * FROM t_role WHERE role_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 * FROM t_role WHERE role_name LIKE CONCAT('%',#{keyword},'%') OR id LIKE CONCAT('%',#{keyword},'%') OR role_type LIKE CONCAT('%',#{keyword},'%') </select>第三种
Mybatis的bind
<!-- 按条件查询用户 -->
<select id="searchData" resultMap="BaseResultMap"> <bind name="pattern" value="searchData + '%'" /> select <include refid="Base_Column_List" /> from user where (name like #{pattern,jdbcType=VARCHAR} or login_name like #{pattern,jdbcType=VARCHAR}) and login_name != #{loginName,jdbcType=VARCHAR} </select>