- 动态sql
xml中代码
<select id="SelectTrends" parameterType="com.***.***.entity.Doctor"
resultMap="BaseResultMap">
select
*
from doctor
<where>
<if test="id != null">
AND id = #{id,jdbcType=VARCHAR}
</if>
<if test="name != null">
AND name = #{name,jdbcType=CHAR}
</if>
</where>
</select>
id为映射类中方法名称,where内条件根据需求增减.查询结果最好使用List接收,避免查询结果为多条时报错.
- 分页查询
方法有很多,可以看https://blog.csdn.net/chenbaige/article/details/70846902的步骤,已经写的很详细.我与他的方法不同:
首先实体类继承一个基类.
实体类中创建基类BaseEntity
public BaseEntity() {
HttpServletRequest request = ((ServletRequestAttributes)
RequestContextHolder.currentRequestAttributes()).getRequest();
String pageSizeStr = request.getParameter("pageSize");
String pageNoStr = request.getParameter("pageNo");
if (StringUtils.isNotBlank(pageSizeStr)) {
int size = Integer.parseInt(pageSizeStr);
this.pageSize = size > 0 ? size : PAGE_SIZE;
} else {
this.pageSize = PAGE_SIZE;
}
if (StringUtils.isNotBlank(pageNoStr)) {
int number = Integer.parseInt(pageNoStr);
this.pageNo = number > 0 ? number - 1 : PAGE_NO;
} else {
this.pageNo = PAGE_NO;
}
this.beginNo = pageNo * pageSize;
}
}
需要分页查询的使其实体类继承BaseEntity,实体类就会含有pageNo(页码),pageSize(每页条数),beginNo(查询起始条数)属性.
controller层传入的参数需要含有pageNo,pageSize属性.
xml中代码
<select id="selectLimit" parameterType="com.***.***.entity.Doctor"
resultMap="BaseResultMap">
select *
from doctor
<where>
**************
</where>
limit #{beginNo},#{pageSize}
</select>
需要注意的是 limit #{beginNo},#{pageSize}中的值名称要与基类中属性名一致.
- List/Array/Map查询
xml中代码
<select id="selectList" parameterType="com.***.***.Entity.Doctor"
resultMap="BaseResultMap">
select * from doctor
<where>
id in
<foreach collection="Ids" item="id" index="index" open="(" close=")"
separator=",">
#{id}
</foreach>
</where>
</select>
实体类中含有属性Ids属性(数据库中很可能无此字段,可以创建新实体类DoctorNew继承Doctor实体类,这样 parameterType="com.***.***.***.DoctorNew").
需要注意的是,当传递的List(或Array,Map)为空时,SQL语句报错,所以传递前最好判断容器内容.
foreach元素的属性主要有(item,index,collection,open,separator,close).
item表示集合中每一个元素进行迭代时的别名
index指定一个名字,用于表示在迭代过程中,每次迭代到的位置
open表示该语句以什么开始
separator表示在每次进行迭代之间以什么符号作为分隔符
close表示以什么结束
collection表示传入参数属性.该属性是必须指定的, 在不同情况下,该属性的值是不一样的,主要有一下3种情况:
1.如果传入的参数是单参数且参数类型是一个List的时候,collection属性值为list .
2.如果传入的参数是单参数且参数类型是一个Array数组的时候,collection的属性值为array .
3.如果传入的参数是多个的时候,可以封装成一个Map,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key.