当前位置:网站首页>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! .
边栏推荐
- 6、 Web Architecture Design
- Tencent cloud arm server evaluation practice
- Summary ranges of leetcode topic resolution
- Interpretation of the most dirty technology in history, I can understand 60 it terms in seconds
- Flink错误--Caused by: org.apache.calcite.sql.parser.SqlParseException: Encountered “time“
- How to use matrix analysis to build your thinking scaffold in flowus, notation and other note taking software
- Geoserver添加mongoDB数据源
- How to use "tomato working method" in flowus, notation and other note taking software?
- JS mask important data of ID card and mobile phone number with * *
- Leetcode topic analysis count primes
猜你喜欢

测试-- 自动化测试selenium(关于API)

Which one is better for rendering renderings? 2022 latest measured data (IV)

Linux Mysql安装

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

Flink错误--Caused by: org.apache.calcite.sql.parser.SqlParseException: Encountered “time“

力扣之滑动窗口《循序渐进》(209.长度最小的子数组、904. 水果成篮)

Hongmeng reads the resource file

自定义标签——jsp标签增强

Monitor the cache update of Eureka client

'coach, I want to play basketball!'—— AI Learning Series booklet for system students
随机推荐
In depth interpretation of poca smart contract platform gear: the road to parallel architecture public chain
Chapter 1 open LDAP master-slave synchronization tower construction
'coach, I want to play basketball!'—— AI Learning Series booklet for system students
Intelligent operation and maintenance exploration | anomaly detection method in cloud system
36氪首发|云原生数据库公司「拓数派」完成新一轮战略融资,估值已达准独角兽级别
Arthas vmtool命令小结
Talk about the implementation principle of @autowired
瞄准海外宠物市场,「Grasphand 」做了一款独立于手机的智能追踪产品 | 早期项目
Monitor the cache update of Eureka client
Summary of communication mode and detailed explanation of I2C drive
6月《中國數據庫行業分析報告》發布!智能風起,列存更生
Point cloud library PCL from introduction to mastery Chapter 10
297. Serialize and Deserialize Binary Tree
Deep analysis and Simulation of vector
Leetcode topic analysis set matrix zeroes
简易学生管理
How to sort a dictionary by value or key?
523. Continuous Subarray Sum
Subsets of leetcode topic resolution
自定义标签——jsp标签增强