Mybatis学习笔记-动态SQL和模糊查询
2017-10-22 14:31
871 查看
上一篇博文把Mybatis关联表查询的一些知识做了一个总结,代码已经发布到Github有兴趣的朋友可以自行下载。平时在做开发的时候,除了多张表查询的问题,还有就是查询时动态拼接SQL以及模糊查询的一些问题,本文就实践和总结一下这方面的问题。
数据结构
![](https://oscdn.geek-share.com/Uploads/Images/Content/202012/14/f42f86752ec8c193983e4993a97a6173)
![](https://oscdn.geek-share.com/Uploads/Images/Content/202012/14/78f64571132c70a5b24e13962df3cf33)
![](https://oscdn.geek-share.com/Uploads/Images/Content/202012/14/0c5a5423fd6c06defcaae6296ee2d037)
原因:mapper文件中定义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时出现重复
相关文章推荐
- myBatis学习笔记(6)——动态SQL & 模糊查询
- Mybatis学习总结之动态SQL与模糊查询
- MyBatis笔记(九)——动态SQL与模糊查询
- MyBatis笔记07 - 动态SQL与模糊查询
- Mybatis学习总结之动态SQL与模糊查询
- Mybatis学习----模糊查询和动态sql
- 【Mybatis学习总结六】动态SQL与模糊查询
- MyBatis学习笔记(五)---mybatis 动态sql语句
- mybatis学习笔记(8)-动态sql
- Mybatis学习笔记——动态Sql
- Mybatis学习笔记(二)-----查询sql的配置文件
- MyBatis学习笔记(六)动态sql
- Mybatis学习笔记之四:动态SQL
- MyBatis的动态SQL的模糊查询
- MyBatis-动态sql与模糊查询 -07
- mybatis学习笔记3 - 动态sql
- Java学习笔记33:mybatis动态SQL语句
- mybatis学习笔记(8)-动态sql
- mybatis的动态SQL与模糊查询
- Mybatis 1.动态sql 2.模糊查询