动态SQL语句。
1.动态SQL:在SQL语句中加入流程控制。比如加入if,foreach等。
重点掌握if语句:
案例1:
<update id="updateItem" parameterType="com.gxa.bj.model.UserInfo">
update userinfo set
<if test="userName!=null">
userName = #{userName},
</if>
<if test="userPwd!=null">
userPwd = #{userPwd},
</if>
<if test= "userEmail!=null">
userEmail = #{userEmail},
</if>
<if test= "userAddress!=null">
userAddress = #{userAddress},
</if>
<if test= "regReason!=null">
regReason = #{regReason},
</if>
userId=#{userId} Where userId=#{userId}
</update>
案例2:
<select id="getList" parameterType="com.gxa.bj.model.UserInfo" resultType="com.gxa.bj.model.UserInfo">
Select * From userInfo Where 1=1
<if test="userName!=null">
And userName like #{userName}
</if>
<if test="userId>0">
And userId =#{userId}
</if>
<if test="userPwd!=null And userPwd!=''">
And userPwd like #{userPwd}
</if>
</select>
2.分页的实现?
分页的时候考虑的问题:
分页的大小,分页的索引。
比如:分页的大小为10,分页的起始索引为1(索引从1开始)
第一页:1到10. 起始行号: (页的索引-1)*分页大小+1
结束行号: 页的索引*分页大小
实现方案:
1)比如针对UserInfo的实体对象做分页处理,那么先创建一个分页的实体类,该类继承自UserInfo。
package com.gxa.bj.model;
public class UserInfoPage extends UserInfo{
// 分页的索引
private int pageIndex;
// 分页的大小
private int pageSize;
// 分页的起始行
private int startNum;
// 分页的结束行
private int endNum;
public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getStartNum() {
return startNum;
}
public void setStartNum(int startNum) {
this.startNum = startNum;
}
public int getEndNum() {
return endNum;
}
public void setEndNum(int endNum) {
this.endNum = endNum;
}
}
2)在接口中定义一个方法,
public List<UserInfo> getListByPage(UserInfoPage upage);
3)在Mapper文件中编写SQL语句:
<select id="getListByPage" parameterType="com.gxa.bj.model.UserInfoPage" resultType="com.gxa.bj.model.UserInfo">
Select u.*
From (Select rownum as num, userinfo.*
from userinfo
<where>
<if test="userName!=null">
And userName like #{userName}
</if>
<if test="userId>0">
And userId =#{userId}
</if>
<if test="userPwd!=null and userPwd !='' ">
And userPwd like #{userPwd}
</if>
</where>
) u Where u.num between #{startNum} and #{endNum}
</select>
4)编写相应的测试代码:
UserInfoPage u= new UserInfoPage();
//
u.setUserName("zhangsan");
u.setPageIndex(2);
u.setPageSize(2);
int startNum = (u.getPageIndex()-1)*u.getPageSize()+1;
int endNum = u.getPageIndex()*u.getPageSize();
u.setStartNum(startNum);
u.setEndNum(endNum);
List<UserInfo> list = userMapper.getListByPage(u);
for(UserInfo t :list){
System.out.println("id:"+t.getUserId());
}