当前位置:网站首页>General paging (1)
General paging (1)
2022-06-23 08:58:00 【An Li Jiu Ge】
Catalog
Two 、 Reflect generic background queries
3、 ... and 、 General paging background query
Preface
Last time we shared custom tags ——jsp Label enhancements , The content shared today is general paging .
One 、PageBean
package com.zhw.util;
public class PageBean {
private int page = 1;// Page number
private int rows = 10;// Page size
private int total = 0;// Total number of records
private boolean pagination = true;// Pagination or not
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;
}
/**
* Get the subscript of the starting record
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
Two 、 Reflect generic background queries
Native :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; }
Reflection :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; }
3、 ... and 、 General paging background query
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";
}Four 、junit4
We often test in main Method to print . There are more and more testing methods ,main Methods are becoming more and more complicated .
You can use Junit.
Right click the test class ,Ctrl+N, Search for junit, Select first .
choice junit 4, And check the setup and teardown

next, Choose Test method of the current class

finish. The test class is finished .

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(" The method under test is called before execution ");
}
@After
public void tearDown() throws Exception {
System.out.println(" Call after the tested method is executed ");
}
@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();
}
}
}
Running results :

If we want to test other methods
Write a new one :


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(" The method under test is called before execution ");
}
@After
public void tearDown() throws Exception {
System.out.println(" Call after the tested method is executed ");
}
@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(" Test code 2");
}
}
give the result as follows :

summary
The content shared this time is the General tab page , Easy to use , If there are multiple types that need to be paged, there is no need to write duplicate code , Just call the written generic paging code , Shorten development time , Reduce the amount of code .
I hope it can help you , General page for next issue preview (2).
I'm nine songs , A programmer who likes programming .
If there is any mistake, please correct it , Thank you very much! .
边栏推荐
- 297. Serialize and Deserialize Binary Tree
- Node request module cookie usage
- MySQL故障案例 | mysqldump: Couldn’t execute ‘SELECT COLUMN_NAME
- 523. Continuous Subarray Sum
- 通用分页(1)
- Utilisation du cookie du module de demande de noeud
- Summary ranges of leetcode topic resolution
- 2022.6.22-----leetcode.513
- 5-rotating Daisy - rotating canvas and timer
- @Response
猜你喜欢

自定义标签——jsp标签基础

【学习资源】理解数学和热爱数学

'coach, I want to play basketball!'—— AI Learning Series booklet for system students

Monitor the cache update of Eureka client

社区文章|MOSN 构建 Subset 优化思路分享

Le rapport d'analyse de l'industrie chinoise des bases de données a été publié en juin. Le vent intelligent se lève, les colonnes se régénèrent

Linux MySQL installation
![[event registration] sofastack × CSDN jointly held the open source series meetup, which was launched on June 24](/img/e1/97c92290a2a5e68f05cdbd5bf525e8.png)
[event registration] sofastack × CSDN jointly held the open source series meetup, which was launched on June 24

GeoServer adding mongodb data source

Point cloud library PCL from introduction to mastery Chapter 10
随机推荐
Optimize your gradle module with a clean architecture
173. Binary Search Tree Iterator
USB peripheral driver - debug
Why is the easycvr Video Fusion platform offline when cascading with the Hikvision platform? How to solve it?
Hongmeng reads the resource file
Vue3表单页面利用keep-alive缓存数据的一种思路
528. Random Pick with Weight
自定义标签——jsp标签增强
6、 Web Architecture Design
Driver Architecture & platform platform bus driver model
力扣之滑动窗口《循序渐进》(209.长度最小的子数组、904. 水果成篮)
(resolved) difference between leftmost prefix and overlay index
4- draw ellipse, use timer
Assembly (receive several n-digit decimal values (0~65535) from the keyboard and display their sum in different base numbers.)
297. Serialize and Deserialize Binary Tree
JS mask important data of ID card and mobile phone number with * *
Single core driver module
Leetcode topic analysis 3sum
65. Valid Number
528. Random Pick with Weight