当前位置:网站首页>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 ~
边栏推荐
- 6 个超级良心的开源教程!
- 18张图,直观理解神经网络、流形和拓扑
- 6 open source tutorials of super conscience!
- DirectX repair tool download (where is exagear simulator package)
- ACM SIGIR 2022 | 美团技术团队精选论文解读
- Array array object
- 22牛客多校day1 I - Chiitoitsu 概论dp
- 华为无线设备配置利用WDS技术部署WLAN业务
- Sdwebimage source code combs 5 author motivation, modifies directory, and changes inheritance relationship
- Symbol symbol type
猜你喜欢

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

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

What if win11 cannot find the DNS address? Win11 can't find DNS and can't access the web page solution

Arduino框架下STM32F103C系列单片机引脚映射关系

Rouyi cloud platform - how to realize the launch and login functions of the project and how to create new modules

Assembly analysis swift polymorphism principle

Thesis reading (2) - vggnet of classification

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

cnpm安装步骤

Why did "you" become a test / development programmer? The value of your existence
随机推荐
Basic concept of MySQL database and deployment of MySQL version 8.0 (I)
Solve the problem of using anonymous users in pod due to the failure of attaching ciphertext token files for serviceaccount user authentication
General principles of software quality
Swift type attribute and its attentions
以流量为主导的数字零售的发展模式,仅仅只是一个开始
22牛客多校day1 I - Chiitoitsu 概论dp
字节8年女测试总监工作感悟—写给想转行或即将进入测试行业的女生们...
Terminal output G_ Debug() information
深开鸿:万物智联的大江上,升起一轮开源鸿蒙月
trivy【3】自定义扫描策略
Mycms we media mall V3.6 release, compatible with micro engine application development (laravel framework)
RouYi-Cloud平台 ---项目的启动、登录功能是怎么实现的、怎么样创建新模块
It's settled! All products of Nezha s will be launched on July 31
一种分布式深度学习编程新范式:Global Tensor
GCD implementation and arc, blocks, GCD usage examples
High quality subroutine 2 - high cohesion
Arduino UNO驱动合宙1.8‘TFT SPI屏幕示例演示(含资料包)
How to automatically install homebrew in China (domestic address)
How strong is this glue?
[physical application] atmospheric absorption loss with matlab code