当前位置:网站首页>General paging - background
General paging - background
2022-07-28 23:30:00 【I love coriander TVT】
Catalog
The focus of general paging is general , Today I'd like to share my understanding of Ge , Paging is divided into foreground and background code , Today, we bring the background code
One 、 generic class BaseDao
1. Get all the methods executeQuery
Three parameters are defined in this method , Respectively, get the original sql Statements and encapsulated paging classes pageBean And a return function interface for processing the result set callBack
In determining whether to page , If you want to page, call this class to get the total number of records CountSQL And how many pieces of data per page PageSQL, Execute the original without paging sql sentence
public List<T> executeQuery( String sql,PageBean pagebean,CallBack<T> callBack) throws Exception{
/**
* 1. Get the database connection
* 2. Get preparstatement
* 3. perform sql sentence
*/
Connection con = DBAccess.getConnection();// Duplicate code 1
PreparedStatement ps = con.prepareStatement(sql);// Duplicate code 2
ResultSet rs = ps.executeQuery();// Duplicate code 3
if(pagebean!=null&&pagebean.isPagination()) {
String countsql = getCountsql(sql);
con = DBAccess.getConnection();
ps = con.prepareStatement(countsql);
rs = ps.executeQuery();
if(rs.next()) {
pagebean.setTotal(rs.getString("n"));
}
String pageSql= getpageSql(sql,pagebean);
con = DBAccess.getConnection();
ps = con.prepareStatement(pageSql);
rs = ps.executeQuery();
}else {
con = DBAccess.getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
}
// Querying different tables must deal with different result sets
return callBack.foreach(rs);
}
The reason why it is universal :
In the collection, replace the specific entity class with letters T It shows that this is a general-purpose entity class that can accommodate any entity class we need , The second is to return the function interface class Collback How to process the result set , Whoever calls this interface class will process the result set
2、 Get the total number of records CountSQL
This is a general method to obtain the total data in the database
/**
* The total number of records that meet the conditions is Sql
* @param sql
* @return
*/
private String getCountsql(String sql) {
// TODO Auto-generated method stub
return "select count(1) as n from ("+sql+") t";
}3、 How many pieces of data per page PageSQL
Get the original sql The method of obtaining subscript and total row number in the page of statement splicing gives a general method of displaying data on the page
/**
* Splice section N Of page data sql
* @param sql
* @param pagebean
* @return
*/
private String getpageSql(String sql, PageBean pagebean) {
return sql +"limit"+pagebean.getStartIndex()+","+pagebean.getRows();
}Two 、 concrete class
Take books as an example , We are reading books Dao in Inherit BaseDao, We just need to return return BaseDao Get all the methods in executeQuery, At the same time, we get three parameters sql,pagebean, as well as CallBack, We just need to put CallBack Replace with the result set of the book , Then traverse the result set of the book
public List<Book> list2(Book book,PageBean pagebean) throws Exception{
List<Book> ls = new ArrayList<Book>();
/**
* 1. Get the database connection
* 2. Get preparstatement
* 3. perform sql sentence
*/
String sql = "select * from t_mvc_book where 1=1";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql +="and bname like'%"+bname+"%'";
}
int bid = book.getBid();
if(bid!=0) {
sql +=" and bid = " +bid;
}
return super.executeQuery(sql, pagebean, rs->{
List<Book> list = new ArrayList<>();
try {
while(rs.next()) {
ls.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
});
}
Next, I will share a method that does not call general methods , Compare it with the general method we call
public List<Book> list(Book book,PageBean pagebean) throws Exception{
List<Book> ls = new ArrayList<Book>();
/**
* 1. Get the database connection
* 2. Get preparstatement
* 3. perform sql sentence
*/
Connection con = DBAccess.getConnection();// Duplicate code 1
String sql = "select * from t_mvc_book where 1=1";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql +="and bname like'%"+bname+"%'";
}
int bid = book.getBid();
if(bid!=0) {
sql +=" and bid = " +bid;
}
PreparedStatement ps = con.prepareStatement(sql);// Duplicate code 2
ResultSet rs = ps.executeQuery();// Duplicate code 3
while(rs.next()) {
ls.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
}
return ls;
}It can be seen with the naked eye that there are a lot of duplicate code , And we call general methods to greatly reduce the duplication of code , It improves our development speed and efficiency , This is the benefit of GM
3、 ... and 、 test
It uses Junit, It can be tested according to a single method , be relative to main In terms of method , The coupling is reduced
There are three ways , Before testing SetUP, After testing TearDown, And one we tested inside TestList Method
Here we only need to instantiate entity classes and paging classes , You can also set the number of pages and total rows by yourself , Then call our method , It's so convenient ! There are three ways to distinguish by marking notes
package com.zjy.dao;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
/**
* junit Be able to test according to a single method
* Compare with main In terms of method , The coupling is reduced
*
*/
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.zjy.entity.Book;
import com.zjy.util.BaseDao;
import com.zjy.util.PageBean;
public class BookDaoTest {
@Before
public void setUp() throws Exception {
System.out.println(" Call before the tested method executes ");
}
@After
public void tearDown() throws Exception {
System.out.println(" Call after the tested method is executed ");
}
/**
* Do not use general methods or paging
*/
@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();
}
}
/**
* Use common methods but not paging
*/
@Test
public void testList2() {
List<Book> list;
try {
list = new BookDao().list2(new Book(), null);
for (Book book : list) {
System.out.println(book);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Use general methods and paging
*/
@Test
public void testList3() {
List<Book> list;
try {
Book b = new Book();
PageBean pageBean = new PageBean();
pageBean.setPage(2);
pageBean.setRows(20);
list = new BookDao().list2(b, pageBean);
for (Book book : list) {
System.out.println(book);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
That's all for today. Bye ~
边栏推荐
- Meet the outbreak period with the integration of transportation and parking, rush for mass production or build a technical moat?
- Price for volume has encountered "six consecutive declines" in sales. Can Volvo, which is no longer safe, turn around?
- Terminal output G_ Debug() information
- 欲要让数字零售继续发挥作用,我们需要对数字零售赋予新的内涵和意义
- 这个胶水有多强呢?
- Symbol symbol type
- 22牛客多校day1 I - Chiitoitsu 概论dp
- Thesis reading (2) - vggnet of classification
- 解决控制文件全部损坏的异常
- WebView whitelist
猜你喜欢

How to embed AI digital human function in VR panorama? Create a cloud experience

Zero vision technology completed the pre-A round of financing and promoted the domestic replacement of intelligent driving platform software

Sqlilabs-3 (entry notes)

Thesis reading (2) - vggnet of classification

18 diagrams, intuitive understanding of neural networks, manifolds and topologies

【物理应用】大气吸收损耗附matlab代码

RouYi-Cloud平台 ---项目的启动、登录功能是怎么实现的、怎么样创建新模块

Basic concept of MySQL database and deployment of MySQL version 8.0 (I)

c语言进阶篇:指针(三)

MySQL常用的日期时间函数
随机推荐
Mgr.exe virus caused the startup program to fail
以流量为主导的数字零售的发展模式,仅仅只是一个开始
GCD implementation and arc, blocks, GCD usage examples
Routeros limited DNS hijacking and check
Terminal output G_ Debug() information
trivy【3】自定义扫描策略
Kotlin function nesting
【图像分割】基于方向谷形检测实现静脉纹路分割附MATLAB代码
这个胶水有多强呢?
Programmer growth Chapter 30: artifact of identifying true and false needs
一种分布式深度学习编程新范式:Global Tensor
参加竞赛同学们的留言 : 第十七届的记忆
[physical application] atmospheric absorption loss with matlab code
High quality subroutine 3 - a good name
Why did "you" become a test / development programmer? The value of your existence
c语言进阶篇:指针(二)
Servlet的使用手把手教学(一)
以价换量却遭遇销量“六连跌”,不再安全的沃尔沃还能翻身吗?
Pgbench benchmark PostgreSQL
Binary search tree