当前位置:网站首页>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 ~
边栏推荐
- Routeros limited DNS hijacking and check
- The development mode of digital retail dominated by traffic is only the beginning
- In order for digital retail to continue to play its role, we need to give new connotation and significance to digital retail
- cnpm安装步骤
- Sqlilabs-1 (breakthrough record)
- Win11快捷复制粘贴不能用怎么办?Win11快捷复制粘贴不能用
- [C language] implementation of three piece chess games
- recursion and iteration
- View APK signature
- Typescript类方法this指针绑定
猜你喜欢

行泊ADAS摄像头前装搭载同比增长54.15%,TOP10供应商领跑

Mycms we media mall V3.6 release, compatible with micro engine application development (laravel framework)

一种分布式深度学习编程新范式:Global Tensor

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

What if win11 cannot find the DNS address? Win11 can't find DNS and can't access the web page solution
![[C language] implementation of three piece chess games](/img/53/7ee14e604c06fd77d65af29d6d92b8.png)
[C language] implementation of three piece chess games

Inheritance in swift

Form label

Win11快捷复制粘贴不能用怎么办?Win11快捷复制粘贴不能用

Nacos配置热更新的4种方式、读取项目配置文件的多种方式,@value,@RefreshScope,@NacosConfigurationProperties
随机推荐
(important) first knowledge of C language -- function
Why did "you" become a test / development programmer? The value of your existence
Huawei wireless device configuration uses WDS technology to deploy WLAN services
Recurrent neural network (RNN)
Typescript类的使用
Sqlilabs-1 (breakthrough record)
【MongoDB】MongoDB数据库的基础使用,特殊情况以及Mongoose的安装和创建流程(含有Mongoose固定版本安装)
Media query adaptation
Solve the exception that all control files are damaged
How does VR panorama entrepreneurship expand the market? How to make the road of entrepreneurship smoother?
Applet, JS, transfer object jump transfer parameter problem
Meet the outbreak period with the integration of transportation and parking, rush for mass production or build a technical moat?
[MySQL series] addition, deletion, modification and query of MySQL tables (Advanced)
被忽视的智能电视小程序领域
Typescript防止基类被实例化
一种分布式深度学习编程新范式:Global Tensor
recursion and iteration
安全狗入选《云安全全景图2.0》多个细项
mgr.exe病毒导致启动程序启动失败
行泊一体迎爆发期,抢量产还是修技术护城河?