前一篇:13-Mybatis封装输出结果之二 – resultMap
https://blog.csdn.net/fsjwin/article/details/109674185
模糊查询,在mybaits中有两种实现方式
1.在java代码中准备好字符串
1.1StudentDao
//使用名字like
public Student selectStudentlike1(String name);
1.2StudentDao.xml
<select id="selectStudentlike1" resultType="com.yuhl.domain.Student">
select id,name,email,age from student where name like #{name}
</select>
1.3测试
@Test
public void test16() {
SqlSession sqlsession = MybatisUtil.getSqlsession();
StudentDao studentDao = sqlsession.getMapper(StudentDao.class);
//可以吧查询的条件放进去,也可以使用一个单独的类ParaObject类封装就可以了。
Student student = studentDao.selectStudentlike1("%张%");
System.out.println(student);
}
1.4测试结果
Checking to see if class com.yuhl.vo.StudentVo matches criteria [is assignable to Object]
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 188576144.
==> Preparing: select id,name,email,age from student where name like ?
==> Parameters: %张%(String)
<== Columns: id, name, email, age
<== Row: 1001, 张三, zhangsan@qq.com, 20
<== Total: 1
Student{id=1001, name='张三', email='zhangsan@qq.com', age=20}
2.在mapper中进行拼接
2.1StudentDao
//使用名字like
public Student selectStudentlike2(String name);
2.2StudentDao.xml
<select id="selectStudentlike2" resultType="com.yuhl.domain.Student">
select id,name,email,age from student where name like "%" #{name} "%"
</select>
2.3测试
@Test
public void test17() {
SqlSession sqlsession = MybatisUtil.getSqlsession();
StudentDao studentDao = sqlsession.getMapper(StudentDao.class);
//可以吧查询的条件放进去,也可以使用一个单独的类ParaObject类封装就可以了。
Student student = studentDao.selectStudentlike2("张");
System.out.println(student);
}
2.4测试结果
Checking to see if class com.yuhl.vo.StudentVo matches criteria [is assignable to Object]
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 188576144.
==> Preparing: select id,name,email,age from student where name like "%" ? "%"
==> Parameters: 张(String)
<== Columns: id, name, email, age
<== Row: 1001, 张三, zhangsan@qq.com, 20
<== Total: 1
Student{id=1001, name='张三', email='zhangsan@qq.com', age=20}
3.总结
使用这两种方式均可以处模糊查询,推荐第一种
- 在java代码中准备好字符串
- 在mapper中进行拼接
脑图https://www.processon.com/view/link/5fae2e01f346fb2d03b384d3
下一篇:15-Mybatis动态sql之一 – <if>标签https://blog.csdn.net/fsjwin/article/details/109675572