今天在做一个mybatis查询的时候有一个需求:分页查询,参数很复杂,首先是分页的两个参数,然后是查询条件的参数,查询条件很多,基本上类里面的属性绝大部分需要用到,我是用的是@param方法,为了方便我的参数是三个:一个实体类,两个分页查询的int类型数据:
// 模糊查询和直接查询使用同一方法,分页查询
public List<MemberStart> select(@Param("mStart") MemberStart mStart, @Param("startRow") int startRow,
@Param("rows") int rows);
这里MemberStart 是我自己写的有一个实体类,我的查询条件基本上就在这个类的属性里面
这里是我的Mapper映射文件:
<select id="select" parameterType="java.util.Map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from memberstart m
where
<if test="mStart.memberId != null">
LOCATE(#{mStart.memberId},m.memberId)
</if>
<if test="mStart.place != null">
and LOCATE(#{mStart.place},m.place)
</if>
<if test="mStart.remark != null">
and LOCATE(#{mStart.remark},m.remark)
</if>
and status = 'A'
limit
#{startRow,jdbcType=INTEGER},
#{rows,jdbcType=INTEGER}
</select>
(先说一下前面这两个文件并没有问题,后面是我的问题所在)
这里是我的controller层:
@ResponseBody
@RequestMapping(value = "/filter.sose", method = RequestMethod.POST, consumes = "application/json;charset=UTF-8")
public Map<String, Object> filter(@RequestBody String c, HttpServletRequest request, HttpSession session) {
java.util.Map<String, Object> map = new HashMap<>();
MemberStart mStart = new MemberStart();
try {
JSONObject strj = new JSONObject(c);
int startRow = strj.getInt("start");
int pageSize = strj.getInt("pageSize");
map.put("list", mStartService.select(mStart, startRow, pageSize));
System.out.println("**************************");
map.put("totalNum", mStartService.selectCount(mStart));
} catch (Exception e) {
map.put("error", e);
}
return map;
}
当我跑起来之后出现这个错误:
Translating SQLException with SQL state '42000', error code '1064', message [You have an
error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'and status = 'A'
limit 0, 10' at line 10]; SQL was [] for task [
我上网百度说是MySQL关键字的问题,仔细查了一下我并没有使用到关键字,我没有办法了,在controller层里面加了几句话:
@ResponseBody
@RequestMapping(value = "/filter.sose", method = RequestMethod.POST, consumes = "application/json;charset=UTF-8")
public Map<String, Object> filter(@RequestBody String c, HttpServletRequest request, HttpSession session) {
java.util.Map<String, Object> map = new HashMap<>();
MemberStart mStart = new MemberStart();
try {
JSONObject strj = new JSONObject(c);
int startRow = strj.getInt("start");
int pageSize = strj.getInt("pageSize");
mStart.setMemberId(1);
mStart.setPlace("");
mStart.setRemark("");
map.put("list", mStartService.select(mStart, startRow, pageSize));
System.out.println("**************************");
map.put("totalNum", mStartService.selectCount(mStart));
} catch (Exception e) {
map.put("error", e);
}
return map;
}
再运行之后就可以了,可见问题出在这个实体类的初始化方面,Mapper映射文件并没有问题,我前面还改了半天的Mapper映射文件,浪费不少时间
在网上看到一种:mybatis的参数还可以是Map类型,不是@param方式的,参数就是Map,把需要用的参数put进去,感兴趣的可以看一下,我改天如果用到这种方式再把这篇博客补一下