上一篇博文把Mybatis关联表查询的一些知识做了一个总结,代码已经发布到Github有兴趣的朋友可以自行下载。平时在做开发的时候,除了多张表查询的问题,还有就是查询时动态拼接SQL以及模糊查询的一些问题,本文就实践和总结一下这方面的问题。
问题需求
实现多条件查询用户(姓名模糊匹配, 年龄在指定的最小值到最大值之间)
测试数据
create table d_user(
id int primary key auto_increment,
name varchar(10),
age int(3)
);
insert into d_user(name,age) values('Tom',12);
insert into d_user(name,age) values('Bob',13);
insert into d_user(name,age) values('Jack',18);
数据结构
创建查询条件对应的实体类
package com.taowd.mybatis.entry;
/**
* 功能:查询条件对应的实体类
* @author Taowd
*
*/
public class ConditionUser {
private String name;
private Integer minAge;
private Integer maxAge;
//set get toString()等方法省略
}
创建表对应的数据实体
public class User {
private int id;
private String name;
private int age;
//set get toString()等方法省略
}
配置Mapper映射文件
<!-- 测试动态SQL和模糊查询 -->
<select id="getUser" parameterType="com.taowd.mybatis.entry.ConditionUser"
resultType="com.taowd.mybatis.entry.User">
select * from d_user where age >= #{minAge} and age<=#{maxAge}
<if test='name!="%null%"'>and name like #{name}</if>
</select>
mybatis配置文件中配置映射文件
<mappers>
<mapper resource="mapper/userMapper.xml" />
</mappers>
测试方法和测试结果
遇到的错误:
错误1:
Mapper文件中定义Sql语句的id时出现重复,执行测试方法时 报错:
原因:mapper文件中定义Sql时出现重复