Mybatis中运用小技巧(二) like的使用

假设要找用户姓名中即含“李”又含“香”的用户,mysql中用like可以解决,语句为:
SELECT * FROM user WHERE u_name LIKE '%李%' and u_name like '%香%';
如果要用Mybatis来实现的话,首先在UserMapper.java中声明一个selectIllegibilityByName方法:
List<User> selectIllegibilityByName(List<String> names);

names是一个由单个字符串组合成的字符串列表,这样我们可以将自己想要查询的字符都添加进去,方法为:

String value = "李香";
List<String> search = new ArrayList<>();
for(int i=0;i<value.length();i++){
	search.add(String.valueOf(value.charAt(i)));
}
而在UserMapper.xml中,我们可以这么实现:
<select id="selectIllegibilityByName" resultMap="BaseResultMap">
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select 
    <include refid="Base_Column_List" />
    from user where
    <foreach item="item" index="index" collection="list" open="(" separator="and" close=")">  
  		u_name like CONCAT('%',#{item},'%') 
 	</foreach>
 	order by id
  </select>

猜你喜欢

转载自blog.csdn.net/u012843873/article/details/80298187