当前位置:网站首页>Generic paging framework
Generic paging framework
2022-06-29 09:49:00 【lion tow】
Today, I want to share a simple framework , General paging :
Catalog
3、 ... and 、Dao Method analysis and examples
One 、 Preparation
We use MySql For the database , Have some entity classes needed in the early stage ……
DBAccess:
package com.zq.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* Provides a set of methods to get or close database objects
*
*/
public class DBAccess {
private static String driver;
private static String url;
private static String user;
private static String password;
static {// The static block executes once , load Drive once
try {
InputStream is = DBAccess.class
.getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(is);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("pwd");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* Get the data connection object
*
* @return
*/
public static Connection getConnection() {
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void close(ResultSet rs) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Statement stmt) {
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn) {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
close(rs);
close(stmt);
close(conn);
}
public static boolean isOracle() {
return "oracle.jdbc.driver.OracleDriver".equals(driver);
}
public static boolean isSQLServer() {
return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
}
public static boolean isMysql() {
return "com.mysql.cj.jdbc.Driver".equals(driver);
}
public static void main(String[] args) {
Connection conn = DBAccess.getConnection();
System.out.println(conn);
DBAccess.close(conn);
System.out.println("isOracle:" + isOracle());
System.out.println("isSQLServer:" + isSQLServer());
System.out.println("isMysql:" + isMysql());
System.out.println(" Database connection ( close ) success ");
}
}
filter :
package com.zq.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Chinese scrambling
*
*/
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// Default character set
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// Chinese processing must be put into chain.doFilter(request, response) Method front
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// Save all parameter names = Parameter values ( Array ) Of Map aggregate
Set set = map.keySet();// Take out all parameter names
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// Take out the parameter value [ notes : The parameter value is an array ]
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// Read web.xml The character set configured in the file
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
Paging tools :
package com.zq.util;
/**
* Paging tool class
*
*/
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 + "]";
}
}
String utility class :
package com.zq.util;
public class StringUtils {
// Private construction method , Protection class cannot be instantiated externally
private StringUtils() {
}
/**
* If the string equals null Or the blank space is equal to "", Then return to true, Otherwise return to false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* If the string is not equal to null Or not equal to... After removing the space "", Then return to true, Otherwise return to false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
The configuration file :
#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#pwd=123
#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1433;DatabaseName=test1
#user=sa
#pwd=123
#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888
#mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/pro?useUnicode=true&characterEncoding=UTF-8&useSSL=false
user=root
pwd=123456
Entity class Book:
package com.zq.entity;
public class Book {
private int bid;
private String bname;
private float price;
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Book() {
// TODO Auto-generated constructor stub
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
}
Of the query Dao Method :
package com.zq.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.zq.entity.Book;
import com.zq.util.BaseDao;
import com.zq.util.CallBack;
import com.zq.util.DBAccess;
import com.zq.util.PageBean;
import com.zq.util.StringUtils;
public class BookDao extends BaseDao<Book> {
public List<Book> list(Book book,PageBean pageBean) throws Exception{
List<Book> list = new ArrayList<Book>();
// Get the database connection
Connection con = DBAccess.getConnection();
// Get the execution object
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;
}
// perform sql sentence
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
list.add(new Book(rs.getInt(1), rs.getString(2),rs.getFloat(3)));
}
return list;
}
// Additions and deletions junit
public static void main(String[] args) throws Exception {
List<Book> list = new BookDao().list(new Book(), null);
for (Book book : list) {
System.out.println(book);
}
}
}
If we do these parts well, our foundation will be completed , The next step is to code the general page !
Basic results :

Two 、 Test tool class Junit
The second content I want to share with you a testing tool class , The function is to write multiple methods in a test class for alternative tests :
① First of all, the first step is to set up when running the same package of the test , If I am here BookDao Build a Junit4, Right click the package or click the BookDao Hold down Ctrl+n

② choice Junit Text Case, Click on Next, Top choice New JUnit 4 text, Below setUp() tearDown() Choose according to your needs , Click on ok You can create a test class

③ Click here to create a test class :
package com.zq.dao;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.zq.entity.Book;
import com.zq.util.PageBean;
/**
* junit Being able to test a single method
* Compare with main In terms of method , Test coupling is reduced
* @author Zhang Qiang
*
* 2022 year 6 month 22 The morning of 9:50:58
*/
public class BookDaoTest {
@Before
public void setUp() throws Exception {
System.out.println(" Called before the tested method is tested ");
}
@After
public void tearDown() throws Exception {
System.out.println(" Called after being tested by the test method ");
}
@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();
}
}
}④ Put the code we want to test into testList() The methods of , Then you can test , The test method : Double click the method name ——》 Right click ——》Run as

advantage : Sure For a single method To test , Compare with main In terms of method , test The coupling is reduced
3、 ... and 、Dao Method analysis and examples
You can see that after we finish the basic code, we still have a lot of duplicate code , Now optimize the duplicate code
We create a generic class , To optimize the code BeseDao.java:
package com.zq.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.zq.entity.Book;
/**
* T Represents an entity class Any entity class
* @author Zhang Qiang
*
* 2022 year 6 month 22 The morning of 9:55:03
*/
public class BaseDao<T> {
public List<T> executeQuery(String sql,PageBean pageBean ,CallBack<T> callBack) throws Exception{
// Get the database connection
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
// Splicing sql Get the total number of records from the above ——》 Get the total number of pages
// Determine if pagination is needed
if(pageBean!= null &&pageBean.isPagination()) {
String countSql = getCountSql(sql);
con = DBAccess.getConnection();
ps = con.prepareStatement(countSql);
rs = ps.executeQuery();
if(rs.next()) {
// The current entity class contains the total number of records
pageBean.setTotal(rs.getString("n"));
}
String pageSQL = getpageSql(sql,pageBean);
con = DBAccess.getConnection();
ps = con.prepareStatement(pageSQL);
rs = ps.executeQuery();
}else {
// No paging
con = DBAccess.getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
}
/**
* We query different tables , The result set is also different , What should we do ?
* We pass the result set to CallBack Interface , Return a collection in the interface
* Handle... In the interface rs
*/
return callBack.foreach(rs);
}
/**
* Assembly No N Of page data Sql
* @param sql
* @param pageBean
* @return
*/
private String getpageSql(String sql, PageBean pageBean) {
return sql+ " limit " + pageBean.getStartIndex() +" , " +pageBean.getRows();
}
/**
* Splicing sql sentence
* @param sql original sql sentence
* @return The last one is SQL Statement to get the total number of data
*/
private String getCountSql(String sql) {
return "select count(1) as n from ("+sql+") t";
}
}
Here you need to implement an interface , So as to handle various calling things CallBack.java
package com.zq.util;
import java.sql.ResultSet;
import java.util.List;
/**
* The role of the callback function interface class
* Who calls who deals with
* @author Zhang Qiang
*
* 2022 year 6 month 22 The morning of 9:56:46
*/
public interface CallBack<T> {
List<T> foreach(ResultSet rs);
}
Here we can change Dao Method , Add the paged content :
public List<Book> list2(Book book,PageBean pageBean) throws Exception{
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()) {
list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
});
}And then OK 了 , Test it , Page the data of the second page directly :
@Test
public void testList3() {
List<Book> list;
try {
Book b = new Book();
PageBean pageBean =new PageBean();
pageBean.setPage(2);
list = new BookDao().list2(b, pageBean);
for (Book book : list) {
System.out.println(book);
}
} catch (Exception e) {
e.printStackTrace();
}
} The result is :
边栏推荐
- [noi Simulation Competition] add points for noi (heavy chain dissection, line segment tree)
- 请用已学过的知识编写程序,找出小甲鱼藏在下边这个长字符串中的密码,密码的埋藏点符合以下规律:
- The principle of session and cookie
- KiCad学习笔记--快捷键
- 安装Anaconda后启动JupyterLab需要输入密码
- Print service IP setting scheme
- Introduction to Chang'an chain data storage and construction of MySQL storage environment
- Do you know what BFD is? This article explains the principle and usage scenarios of BFD protocol in detail
- MySQL configuring master-slave databases
- Research progress of target detection in the era of deep convolutional neural network
猜你喜欢

linux环境下安装配置redis,并设置开机自启动

Simplicity Studio无法识别新买的JLink v9解决方法

UE4 compile a single file (VS and editor start respectively)

用户级线程和内核级线程

1.4 regression of machine learning methods

UE4 材质UV纹理不随模型缩放拉伸

Student增删gaih

UE4 installs the datasmith plug-in in version 4.20-23

Simplicity studio does not recognize the new JLINK V9 solution

1424. 对角线遍历 II
随机推荐
UE4 remove the mask transparent white edge in the material
Pytorch summary learning series - broadcast mechanism
云管理平台:OpenStack架构设计及详细解读
Twinmotion beginner tutorial
请用已学过的知识编写程序,找出小甲鱼藏在下边这个长字符串中的密码,密码的埋藏点符合以下规律:
Research progress of target detection in the era of deep convolutional neural network
数据可视化:数据可视化的意义
Data visualization: the four quadrants of data visualization teach you to correctly apply icons
c#判断数组是否包含另一个数组的任何项
Implementation of multi key state machine based on STM32 standard library
Pytorch Summary - Automatic gradient
云管理平台:9大开源云管理平台(CMP)
Is it safe to open an account for stock speculation? Is it reliable?
[technology development] development and design of alcohol tester solution
Es error nonodeavailableexception[none of the configured nodes are available:[.127.0.0.1}{127.0.0.1:9300]
Construction and use of Changan chain go language smart contract environment
es报错NoNodeAvailableException[None of the configured nodes are available:[.127.0.0.1}{127.0.0.1:9300]
UE4 material UV texture does not stretch with model scale
UE4 动画重定向
367. 有效的完全平方数-二分法