java之mybatis之模糊查询

时间:2023-02-04 22:50:00

1.在 mybatis 中,模糊查询可以有以下方式

(1).第一种,直接将封装好的条件传给 sql 语句

<select id="findByName" parameterType="string" resultType="User">
select * from t_user where name like #{name}
</select>

代码

@Test
public void testFindLike() throws IOException{
SqlSession session = MybatisUtil.getSqlSession();
List<User> list = session.selectList("cn.sxt.vo.UserMapper.findByName","张%");
for(User u:list){
System.out.println(u);
}
session.close();
}

(2)第二种, 使用字符串连接符 ${} 来实现

<select id="findByName1" parameterType="Map" resultType="User">
select * from t_user where name like '${name}%'
</select>

代码

  @Test
public void testFindLike1() throws IOException{
SqlSession session = MybatisUtil.getSqlSession();
Map map = new HashMap();
map.put("name", "张");
List<User> list = session.selectList("cn.sxt.vo.UserMapper.findByName1",map);
for(User u:list){
System.out.println(u);
}
session.close();
}

(3)第三种,使用 mysql 的字符串拼接函数实现

<select id="findByName2" parameterType="string" resultType="User">
select * from t_user where name like concat(#{name},'%')
</select>

代码

  @Test
public void testFindLike2() throws IOException{
SqlSession session = MybatisUtil.getSqlSession();
List<User> list = session.selectList("cn.sxt.vo.UserMapper.findByName2","张");
for(User u:list){
System.out.println(u);
}
session.close();
}