过去工作的几年一直使用的oracle,如今改成mysql,感觉有点不大习惯,在这里将昨天写的mysql+mybatis分页记录一下
user.xml
<select id="getUserPageList" resultType="UserDO"
parameterType="com.zhibi.data.api.jhs.param.UserSearchParam">
select * from user
<where>
<if test="phoneNum!=null and phoneNum!=''"> phoneNum like CONCAT(#{phoneNum} ,'%') </if>
<if test="nickName!=null and nickName!=''"> and nickName like CONCAT(#{nickName},'%') </if>
<if test="startDate!=null"> and gmtCreate > #{startDate}</if>
<if test="endDate!=null"> and gmtCreate < #{endDate}</if>
</where>
order by
<if test="orderField!=null and orderField!=''"> ${orderField} ${order}, </if>
gmtCreate desc limit #{pageNo},#{pageSize}
</select>
<select id="countPageList" resultType="int"
parameterType="com.zhibi.data.api.jhs.param.UserSearchParam">
select count(*) from (
select * from user
<where>
<if test="phoneNum!=null and phoneNum!=''"> phoneNum like CONCAT(#{phoneNum} ,'%') </if>
<if test="nickName!=null and nickName!=''"> and nickName like CONCAT(#{nickName},'%') </if>
<if test="startDate!=null"> and gmtCreate > #{startDate}</if>
<if test="endDate!=null"> and gmtCreate < #{endDate}</if>
</where>
)resultList
</select>
遇到的一些问题:
- 模糊查询。在oracle中模糊查询只需要 #{phoneNum}||‘%’就可以了,但是放在mysql中不管用,必须concat拼接起来
- 子查询结果列表取别名,在求结果总条数的时候,需要对结果基求count,发现不加resultList别名会报错,oracle就可以不加
- 日期的加减必须通过date_add和date_sub函数完成,不能直接加减,如
select DATE_sub(now() ,INTERVAL 1 DAY)from dual;--昨天
select date_add(now(),interval 1 day); --明天
日期格式化 date_format,而不是to_char,且格式表达式不一样,mysql中:
%S, %s 两位数字形式的秒( 00,01, …, 59)%i 两位数字形式的分( 00,01, …, 59)
%H 两位数字形式的小时,24 小时(00,01, …, 23)
%h, %I 两位数字形式的小时,12 小时(01,02, …, 12)
%k 数字形式的小时,24 小时(0,1, …, 23)
%l 数字形式的小时,12 小时(1, 2, …, 12)
%T 24 小时的时间形式(h h : m m : s s)
%r 12 小时的时间形式(hh:mm:ss AM 或hh:mm:ss PM)
%p AM 或P M
%W 一周中每一天的名称( S u n d a y, Monday, …, Saturday)
%a 一周中每一天名称的缩写( Sun, Mon, …, Sat)
%d 两位数字表示月中的天数( 00, 01, …, 31)
%e 数字形式表示月中的天数( 1, 2, …, 31)
%D 英文后缀表示月中的天数( 1st, 2nd, 3rd, …)
%w 以数字形式表示周中的天数( 0 = S u n d a y, 1=Monday, …, 6=Saturday)
%j 以三位数字表示年中的天数( 001, 002, …, 366)
% U 周(0, 1, 52),其中Sunday 为周中的第一天
%u 周(0, 1, 52),其中Monday 为周中的第一天
%M 月名(J a n u a r y, February, …, December)
%b 缩写的月名( J a n u a r y, February, …, December)
%m 两位数字表示的月份( 01, 02, …, 12)
%c 数字表示的月份( 1, 2, …, 12)
%Y 四位数字表示的年份
%y 两位数字表示的年份
%% 直接值“%”
如:
select DATE_FORMAT(NOW(),'%Y-%m-%d') from DUAL;
--结果 2016-07-14
xml中大于号小于号有特殊意义需要转义
排序时因为是$取值,有安全隐患,可以在取值的时候做校验,如:
public String getOrderField() {
if(orderField.indexOf(" ")>-1){
return "";
}
return orderField;
}
public void setOrderField(String orderField) {
this.orderField = orderField;
}
public String getOrder() {
if(!"desc".equalsIgnoreCase(order)){
return "ASC";
}
return "DESC";
}