1.动态SQL:在SQL语句中加入流程控制。比如加入if,foreach等。
重点掌握if语句:
案例1:
-
"updateItem" parameterType=
"com.gxa.bj.modle.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>
-
userId=#{userId} where userId=#{userId}
-
实现列:
-
UserInfo u=
new UserInfo();
-
u.setUserId(
7);
-
u.setUserName(
"李大名");
-
u.setUserPwd(
"123");
-
u.setUserEmail(
"[email protected]");
-
userMapper.updateItem(u);
-
sqlSessin.commit();
-
System.out.println(
"修改成功");
案列2:
-
-
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 #{userName}
-
if>
-
实现列:
-
u.setUserName(
"小白");
-
List
list= userMapper.getList(u);
-
for(UserInfo u1:list){
-
System.out.println(
"用户信息:"+u1.getUserPwd());
-
}
2.分页的实现?
分页的时候考虑的问题:
分页的大小,分页的索引。
比如:分页的大小为10,分页的起始索引为1(索引从1开始)
第一页:1到10. 起始行号: (页的索引-1)*分页大小+1
结束行号: 页的索引*分页大小
实现方案:
1)比如针对UserInfo的实体对象做分页处理,那么先创建一个分页的实体类,该类继承自UserInfo package com.gxa.bj.modle
-
package com.gxa.bj.modle;
-
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 getListByPage(UserInfoPage upage) ;
3)在Mapper文件中编写SQL语句:
-
-
select u.*
-
From(select rownum as num, userinfo.*
-
from userinfo
-
-
<
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 #{userName}
-
if>
-
-
) u where u.num between #{startNum}and#{endNum}
-
4)测试代码:
-
UserInfoPage u1=
new UserInfoPage();
-
u1.setUserName(
"userName");
-
u1.setPageIndex(
2);
//查询第几页
-
u1.setPageSize(
2);
//分布每页的条数
-
int startNum=(u1.getPageIndex()-
1)*u1.getPageSize()+
1;
-
int endNum=u1.getPageIndex()*u1.getPageSize();
-
u1.setStartNum(startNum);
-
u1.setEndNum(endNum);
-
List
list=userMapper.getListByPage(u1);
-
for(UserInfo t :list){
-
System.out.println(
"id:"+t.getUserId());
-
}