当前位置:网站首页>通用分页(1)
通用分页(1)
2022-06-23 08:40:00 【安离九歌】
目录
前言
上次我们分享了自定义标签——jsp标签增强,今天分享的内容是通用分页。
一、PageBean
package com.zhw.util;
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
二、反射通用后台查询
原生:public List<Book> list(Book book,PageBean pageBean) throws Exception{ List<Book> list = new ArrayList<Book>(); Connection con = DBAccess.getConnection(); String sql = "select * from t_mvc_book where 1=1 "; String bname = book.getBname(); if(StringUtils.isNotBlank(bname)) { sql += "and bname like '%"+bname+"%' "; } PreparedStatement pst = con.prepareStatement(sql); ResultSet rs = pst.executeQuery(); while(rs.next()) { list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price"))); } return list; }
反射:public List<T> list(String sql,Class<T> clz) throws Exception{ List<T> list = new ArrayList<T>(); Connection con = DBAccess.getConnection(); String sql = "select * from t_mvc_book where 1=1 "; String bname = book.getBname(); if(StringUtils.isNotBlank(bname)) { sql += "and bname like '%"+bname+"%' "; } PreparedStatement pst = con.prepareStatement(sql); ResultSet rs = pst.executeQuery(); while(rs.next()) { // list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price"))); T t = clz.newInstance(); Field[] fields = clz.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); f.set(t, rs.getObject(f.getName())); } list.add(t); } return list; }
三、通用的分页后台查询
public List<T> executeQuery(String sql,PageBean pageBean,Class<T> clz) throws Exception{
List<T> list = new ArrayList<T>();
Connection con = DBAccess.getConnection();
PreparedStatement pst = null;
ResultSet rs = null;
String countSQL = getCountSQL(sql);
String pageSQL = getPageSQL(sql,pageBean);
if(pageBean != null && pageBean.isPagination()) {
pst = con.prepareStatement(countSQL);
rs = pst.executeQuery();
if(rs.next()) {
pageBean.setTotal(String.valueOf(rs.getObject(1)));
}
pst = con.prepareStatement(pageSQL);
rs = pst.executeQuery();
}else {
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
}
while(rs.next()) {
// list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
T t = clz.newInstance();
Field[] fields = clz.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
f.set(t, rs.getObject(f.getName()));
}
list.add(t);
}
return list;
}
private String getPageSQL(String sql, PageBean pageBean) {
return sql + " limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
private String getCountSQL(String sql) {
return "select count(1) FROM ("+sql+") t";
}四、junit4
我们测试的时候经常会在main方法中打印。测试的方法越来越多,main方法也越来越杂。
这时候就可以用到Junit。
在测试类右键,Ctrl+N, 搜索junit,选择第一个。
选择junit 4,并勾选setup和teardown

next,选中 当前类的测试方法

finish。测试类就完成了。

package com.zhw.dao;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.zhw.entity.Book;
public class BookDaoTest {
@Before
public void setUp() throws Exception {
System.out.println("被测试方法执行前调用");
}
@After
public void tearDown() throws Exception {
System.out.println("被测试方法执行后调用");
}
@Test
public void testList() {
List<Book> list;
try {
list = new BookDao().list(new Book(), null);
for (Book book : list) {
System.out.println(book);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果:

如果我们要测试其他方法
新写一个:


package com.zhw.dao;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.zhw.entity.Book;
public class BookDaoTest {
@Before
public void setUp() throws Exception {
System.out.println("被测试方法执行前调用");
}
@After
public void tearDown() throws Exception {
System.out.println("被测试方法执行后调用");
}
@Test
public void testList() {
List<Book> list;
try {
list = new BookDao().list(new Book(), null);
for (Book book : list) {
System.out.println(book);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testList2() {
System.out.println("测试代码2");
}
}
结果如下:

总结
这次分享的内容是通用标签分页,便于使用,如果有多个类型需要分页则不需要写重复代码,只需调用写好的通用分页代码,缩短了开发时间,减少代码量。
希望对你能有帮助,下期预告通用分页(2)。
我是九歌,一个喜欢编程的程序员。
如有错误还望指正,谢谢啦。
边栏推荐
- 4- draw ellipse, use timer
- Optimize your gradle module with a clean architecture
- Leetcode topic analysis set matrix zeroes
- 测试-- 自动化测试selenium(关于API)
- Go data types (II) overview of data types supported by go and Boolean types
- Leetcode topic analysis spiral matrix II
- (resolved) difference between leftmost prefix and overlay index
- Install a WGet for your win10
- Arclayoutview: implementation of an arc layout
- [QNX Hypervisor 2.2用户手册]5.6.1 Guest关机时静默设备
猜你喜欢

【活动报名】SOFAStack × CSDN 联合举办开源系列 Meetup ,6 月 24 日火热开启

Object. Defineproperty() and data broker

173. Binary Search Tree Iterator

“方脸老师”董宇辉再回应热度下降:把农产品直播做好让农民受益 考虑去支教

297. Serialize and Deserialize Binary Tree

Linux Mysql安装

【云计算】GFS思想优势以及架构
![Paper reading [quovadis, action recognition? A new model and the dynamics dataset]](/img/3f/449cc91bfa66fcf26bc2cd405fb773.png)
Paper reading [quovadis, action recognition? A new model and the dynamics dataset]

The rtsp/onvif protocol video platform easynvr startup service reports an error "service not found". How to solve it?

6月《中國數據庫行業分析報告》發布!智能風起,列存更生
随机推荐
6、 Web Architecture Design
Arclayoutview: implementation of an arc layout
给你的win10装一个wget
Object.defineProperty() 和 数据代理
Single core driver module
[QNX Hypervisor 2.2用户手册]6.1 使用QNX Hypervisor系统
Subsets II of leetcode topic analysis
173. Binary Search Tree Iterator
Geoserver添加mongoDB数据源
Flutter achieves the effect of selecting seats in the cinema!
【活动报名】SOFAStack × CSDN 联合举办开源系列 Meetup ,6 月 24 日火热开启
Unity grid programming 08
Testing -- automated testing selenium (about API)
[qnx hypervisor 2.2 user manual]5.6.1 silent device during guest shutdown
636. Exclusive Time of Functions
词性家族
'教练,我想打篮球!' —— 给做系统的同学们准备的 AI 学习系列小册
125. Valid Palindrome
297. Serialize and Deserialize Binary Tree
Deep analysis and Simulation of vector