传统数据分页
MyBatis编程方式实现
- StudentMapper.java
public interface StudentMapper {
public int count(); //查询数据总数
/*查询分页数据*/
public List<Map<String, Object>> page(@Param("start") int start,@Param("pagesize") int pagesize);
public List<Map<String, Object>> page();
}
- StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.tang.mapper.StudentMapper"> <!--对应的mapper接口文件-->
<select id="page" resultType="map">
select id,name from t_student limit
<if test="start!=null and pagesize!=null">
#{start},#{pagesize}
</if>
<if test="start==null and pagesize==null">
0,2
</if>
</select>
<select id="count" resultType="int">
select count(*) from t_student
</select>
</mapper>
- Text.java
public static void main2(String[] args) throws IOException {
//建立数据源,使用阿里连接池
//通过读取properties文件来加载数据库信息
InputStream in= Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
Properties pro = new Properties();
//或者:pro.load(Resources.getResourceAsReader("db.properties")); //来加载文件流
pro.load(in);
//阿里连接池加载数据库配置
DruidDataSource ds = new DruidDataSource();
ds.setConnectProperties(pro);
//建立事务管理对象
TransactionFactory tx = new JdbcTransactionFactory();
//建立mybatis环境
Environment env = new Environment("development", tx, ds);
//建立配置对象,相当于加个mybatis-config.xml
Configuration cfg = new Configuration(env);
//加载指定的一个接口类,没有下面直接加载所有类好
//cfg.addMapper(UserMapper.class);
//直接加载cn.webrx.mapper 包下的所有接口类,及相同名称的映射文件xml
cfg.addMappers("cn.tang.mapper");
//以下步骤开始跟mybatis-config.xml配置方式一样处理
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(cfg);
SqlSession ss = sf.openSession();
//获取指定接口类
StudentMapper sm = ss.getMapper(StudentMapper.class);
//调用类中方法测试 sm.XXX
System.out.println(sm.query());
int conut = sm.count(); //查询总记录数
System.out.println(conut);
System.out.println(sm.page()); //分页无参查询测试
int currpage = 3; //查询第几页
int pagesize = 3; //每页多少条
int start = currpage * pagesize - pagesize; //计算跳转到第几页
int pagecount = conut % pagesize == 0 ? conut/pagesize : conut/pagesize+1; //总页数
System.out.println(sm.page(start,pagesize)); //分页有参查询
System.out.println("-".repeat(60));
System.out.printf("【第%d页,共%d页】【每页%d条,共%d条】",currpage,pagecount,pagesize,conut);
ss.commit();
}
4.结果展示

这篇博客介绍了如何使用 MyBatis 框架进行传统的数据分页查询。示例展示了 StudentMapper 接口及其 XML 映射文件中的查询方法,包括查询数据总数和分页查询。在 Text.java 类中,展示了如何配置数据源、事务管理,以及如何通过 SqlSession 获取分页数据。最后,展示了查询结果和分页信息的输出。

864

被折叠的 条评论
为什么被折叠?



