当前位置:网站首页>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 ~
边栏推荐
- What if win11 cannot find the DNS address? Win11 can't find DNS and can't access the web page solution
- 22牛客多校day1 J - Serval and Essay 启发式合并
- mgr.exe病毒导致启动程序启动失败
- 【MongoDB】MongoDB数据库的基础使用,特殊情况以及Mongoose的安装和创建流程(含有Mongoose固定版本安装)
- Why did "you" become a test / development programmer? The value of your existence
- cnpm安装步骤
- Basic concept of MySQL database and deployment of MySQL version 8.0 (I)
- Symbol symbol type
- High quality subroutine 3 - a good name
- [copy] Internet terms, abbreviations, abbreviations
猜你喜欢
![[physical application] Wake induced dynamic simulation of underwater floating wind turbine wind field with matlab code](/img/31/e4cd4c261a7fc5cfa731976314530b.png)
[physical application] Wake induced dynamic simulation of underwater floating wind turbine wind field with matlab code

Messages from students participating in the competition: memories of the 17th session
![[radar] radar signal online sorting based on kernel clustering with matlab code](/img/56/1f8e8690b47fc4a1f101d4e530b87f.png)
[radar] radar signal online sorting based on kernel clustering with matlab code

【MySQL系列】 MySQL表的增删改查(进阶)

【滤波跟踪】基于EKF、时差和频差定位实现目标跟踪附matlab代码

行泊一体迎爆发期,抢量产还是修技术护城河?

Performance optimized APK slimming

深开鸿:万物智联的大江上,升起一轮开源鸿蒙月

A new MPLS note from quigo, which must be read when taking the IE exam ---- quigo of Shangwen network

Win11找不到DNS地址怎么办?Win11找不到DNS无法访问网页解决方法
随机推荐
How does VR panorama entrepreneurship expand the market? How to make the road of entrepreneurship smoother?
High quality subroutine 2 - high cohesion
[image segmentation] vein segmentation based on directional valley detection with matlab code
Arduino UNO驱动合宙1.8‘TFT SPI屏幕示例演示(含资料包)
Research on cookies in WebView
MyCms 自媒体商城 v3.6 发布,兼容微擎应用开发(Laravel框架)
安全狗入选《云安全全景图2.0》多个细项
sql优化常用的几种方法
行泊一体迎爆发期,抢量产还是修技术护城河?
【滤波跟踪】基于EKF、时差和频差定位实现目标跟踪附matlab代码
The safety dog has been selected into many details of cloud security panorama 2.0
通过Wi-Fi 7实现极高吞吐量——洞察下一代Wi-Fi物理层
Typescript类方法this指针绑定
Mgr.exe virus caused the startup program to fail
《MySQL数据库进阶实战》读后感(SQL 小虚竹)
[copy] Internet terms, abbreviations, abbreviations
解决控制文件全部损坏的异常
Hbuilderx shortcut key
这款全网热评的无线路由器,到底有什么特别?
参加竞赛同学们的留言 : 第十七届的记忆