当我们需要进行模糊查询时候 一般会遇到一些问题
例如 sql 拼接时候 出现了
select * from student
<if test="sname !=null and sname !=''">
and sname like '%${sname}%'
</if>
<if test="sage !=null and sage !='' ">
and sage like '%${sage}%'
</if>
第一个and的处理 则很关键。<trim>就为我们提供了这一问题的解决。
下面是StudentMapper.xml 我们来写下sql语句
实现模糊查询的三种方式:
#{} :自动附加 ‘ ’
${}:传什么值就替换什么值
bind:做绑定 类似于System.out.println();中的拼接
<select id="queryStudentWithONGL" parameterType="student"
resultType="student">
select * from student
<trim prefix="where" prefixOverrides="and">
<!-- bind实现模糊查询 -->
<bind name="_queryName" value="'%'+sname+'%'"/>
<if test="sname !=null and sname !=''">
and sname like #{_queryName}
</if>
<if test="sage !=null and sage !='' ">
and sage like '%${sage}%'
</if>
</trim>
</select>
<trim>为我们提供了
分别对应的是 sql前 和 后 的代码处理。我们的例子中 <trim prefix="where" prefixOverrides="and"> 就是处理where中 前面 and的处理
接口:
List<Student> queryStudentWithONGL(Student student);
测试类:
//tirm标签 模糊查询
public static void queryStudentWithONGL() throws IOException {
Reader reader = Resources.getResourceAsReader("config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
/* 1.实现接口
* 2.然后接口文件的名称 与 xml中的namespace形成映射 自动绑定配置
*/
StudentMapper studentmapper = session.getMapper(StudentMapper.class);
Student student = new Student("c",20);
List<Student> students = studentmapper.queryStudentWithONGL(student);
System.err.println(students);
session.close();
}
结果: