一、Mysql中分页语法
select * from emp limit startIndex,pageSize
startIndex
:从哪一条数据开始,第一条数据下标为0
pageSize
:查询数据的偏移量(从startIndex开始查询多少条数据)
二、在Mybatis实现分页查询
2.1、数据库字段:
2.2、实体类
public class Emp {
public int eid;
public String ename;
public String esex;
public String salry;
public Emp(int eid, String ename, String esex, String salry) {
this.eid = eid;
this.ename = ename;
this.esex = esex;
this.salry = salry;
}
public Emp() {
}
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getEsex() {
return esex;
}
public void setEsex(String esex) {
this.esex = esex;
}
public String getSalry() {
return salry;
}
public void setSalry(String salry) {
this.salry = salry;
}
@Override
public String toString() {
return "Emp{" +
"eid=" + eid +
", ename='" + ename + '\'' +
", esex='" + esex + '\'' +
", salry='" + salry + '\'' +
'}';
}
}
2.3、接口函数
List<Emp> selectForPage(Map<String,Object> map);
2.4、mapper.xml
<resultMap id="EmpMap" type="Emp">
<result column="esalry" property="salry"></result>
</resultMap>
<select id="selectForPage" parameterType="map" resultMap="EmpMap">
select * from emp limit #{startIndex},#{pageSize};
</select>
这里数据库字段和实体类字段不一样,不一样的字段的查询会为null
,这里来添加resultMap
进行字段映射,不一样的字段名为esalry
,column
表示数据库的字段,property
表示实体类设置的字段,除了使用resultMap
,还可以在查询过程中给字段取别名,当然建议使用前者
2.5、测试
@Test
public void selectForPage(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
EmpMapper mapper = sqlSession.getMapper(EmpMapper.class);
Map<String,Object> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",3);
List<Emp> emps = mapper.selectForPage(map);
for (Emp emp:emps){
System.out.println(emp);
}
sqlSession.close();
}
2.6、查询结果
三、万能的Map
上面传递startIndex
和pageSize
参数时用到了Map集合,当数据库字段名比较多时建议使用Map传参,好处就是不用new出所有的字段(当然可以添加多个构造或着set进去),但使用Map集合非常方便,在sql查询需要的参数只需要填Map对应的键,会根据对应的键取到值
结尾附上mybatis类型的别名
别名 映射的类型
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator