栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

MyBatis3-实现MyBatis分页,零基础如何成为高级Java开发

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MyBatis3-实现MyBatis分页,零基础如何成为高级Java开发

this.showCount = showCount;

}

public int getTotalPage() {

return totalPage;

}

public void setTotalPage(int totalPage) {

this.totalPage = totalPage;

}

public int getTotalResult() {

return totalResult;

}

public void setTotalResult(int totalResult) {

this.totalResult = totalResult;

}

public int getCurrentPage() {

return currentPage;

}

public void setCurrentPage(int currentPage) {

this.currentPage = currentPage;

}

public int getCurrentResult() {

return currentResult;

}

public void setCurrentResult(int currentResult) {

this.currentResult = currentResult;

}

public String getSortField() {

return sortField;

}

public void setSortField(String sortField) {

this.sortField = sortField;

}

public String getOrder() {

return order;

}

public void setOrder(String order) {

this.order = order;

}

}

ReflectHelper.java:

package com.jsoft.testmybatis.util;

import java.lang.reflect.Field;

public class ReflectHelper {

public static Field getFieldByFieldName(Object obj, String fieldName) {

for (Class superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {

try {

return superClass.getDeclaredField(fieldName);

} catch (NoSuchFieldException e) {

}

}

return null;

}

public static Object getValueByFieldName(Object obj, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {

Field field = getFieldByFieldName(obj, fieldName);

Object value = null;

if (field != null) {

if (field.isAccessible()) {

value = field.get(obj);

} else {

field.setAccessible(true);

value = field.get(obj);

field.setAccessible(false);

}

}

return value;

}

public static void setValueByFieldName(Object obj, String fieldName, Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {

Field field = obj.getClass().getDeclaredField(fieldName);

if (field.isAccessible()) {

field.set(obj, value);

} else {

field.setAccessible(true);

field.set(obj, value);

field.setAccessible(false);

}

}

}

PagePlugin.java:

package com.jsoft.testmybatis.util;

import java.lang.reflect.Field;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

import java.util.Map;

import java.util.Properties;

import javax.xml.bind.PropertyException;

import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;

import org.apache.ibatis.executor.ErrorContext;

import org.apache.ibatis.executor.ExecutorException;

import org.apache.ibatis.executor.statement.baseStatementHandler;

import org.apache.ibatis.executor.statement.RoutingStatementHandler;

import org.apache.ibatis.executor.statement.StatementHandler;

import org.apache.ibatis.mapping.BoundSql;

import org.apache.ibatis.mapping.MappedStatement;

import org.apache.ibatis.mapping.ParameterMapping;

import org.apache.ibatis.mapping.ParameterMode;

import org.apache.ibatis.plugin.Interceptor;

import org.apache.ibatis.plugin.Intercepts;

import org.apache.ibatis.plugin.Invocation;

import org.apache.ibatis.plugin.Plugin;

import org.apache.ibatis.plugin.Signature;

import org.apache.ibatis.reflection.metaObject;

import org.apache.ibatis.reflection.property.PropertyTokenizer;

import org.apache.ibatis.session.Configuration;

import org.apache.ibatis.type.TypeHandler;

import org.apache.ibatis.type.TypeHandlerRegistry;

@Intercepts({ @Signature(type = StatementHandler.class, method = “prepare”, args = { Connection.class, Integer.class }) })

public class PagePlugin implements Interceptor {

private static String dialect = “”;

private static String pageSqlId = “”;

@SuppressWarnings(“unchecked”)

public Object intercept(Invocation ivk) throws Throwable {

if (ivk.getTarget() instanceof RoutingStatementHandler) {

RoutingStatementHandler statementHandler = (RoutingStatementHandler) ivk.getTarget();

baseStatementHandler delegate = (baseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, “delegate”);

MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, “mappedStatement”);

if (mappedStatement.getId().matches(pageSqlId)) {

BoundSql boundSql = delegate.getBoundSql();

Object parameterObject = boundSql.getParameterObject();

if (parameterObject == null) {

throw new NullPointerException(“parameterObject error”);

} else {

Connection connection = (Connection) ivk.getArgs()[0];

String sql = boundSql.getSql();

String countSql = “select count(0) from (” + sql + “) myCount”;

System.out.println

《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享

(“总数sql 语句:” + countSql);

PreparedStatement countStmt = connection.prepareStatement(countSql);

BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);

setParameters(countStmt, mappedStatement, countBS, parameterObject);

ResultSet rs = countStmt.executeQuery();

int count = 0;

if (rs.next()) {

count = rs.getInt(1);

}

rs.close();

countStmt.close();

PageInfo page = null;

if (parameterObject instanceof PageInfo) {

page = (PageInfo) parameterObject;

page.setTotalResult(count);

} else if (parameterObject instanceof Map) {

Map map = (Map) parameterObject;

page = (PageInfo) map.get(“page”);

if (page == null)

page = new PageInfo();

page.setTotalResult(count);

} else {

Field pageField = ReflectHelper.getFieldByFieldName(parameterObject, “page”);

if (pageField != null) {

page = (PageInfo) ReflectHelper.getValueByFieldName(parameterObject, “page”);

if (page == null)

page = new PageInfo();

page.setTotalResult(count);

ReflectHelper.setValueByFieldName(parameterObject, “page”, page);

} else {

throw new NoSuchFieldException(parameterObject.getClass().getName());

}

}

String pageSql = generatePageSql(sql, page);

System.out.println(“page sql:” + pageSql);

ReflectHelper.setValueByFieldName(boundSql, “sql”, pageSql);

}

}

}

return ivk.proceed();

}

private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {

ErrorContext.instance().activity(“setting parameters”).object(mappedStatement.getParameterMap().getId());

List parameterMappings = boundSql.getParameterMappings();

if (parameterMappings != null) {

Configuration configuration = mappedStatement.getConfiguration();

TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();

metaObject metaObject = parameterObject == null ? null : configuration.newmetaObject(parameterObject);

for (int i = 0; i < parameterMappings.size(); i++) {

ParameterMapping parameterMapping = parameterMappings.get(i);

if (parameterMapping.getMode() != ParameterMode.OUT) {

Object value;

String propertyName = parameterMapping.getProperty();

PropertyTokenizer prop = new PropertyTokenizer(propertyName);

if (parameterObject == null) {

value = null;

} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {

value = parameterObject;

} else if (boundSql.hasAdditionalParameter(propertyName)) {

value = boundSql.getAdditionalParameter(propertyName);

} else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) {

value = boundSql.getAdditionalParameter(prop.getName());

if (value != null) {

value = configuration.newmetaObject(value).getValue(propertyName.substring(prop.getName().length()));

}

} else {

value = metaObject == null ? null : metaObject.getValue(propertyName);

}

TypeHandler typeHandler = parameterMapping.getTypeHandler();

if (typeHandler == null) {

throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());

}

typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());

}

}

}

}

private String generatePageSql(String sql, PageInfo page) {

if (page != null && (dialect != null || !dialect.equals(""))) {

StringBuffer pageSql = new StringBuffer();

if (“mysql”.equals(dialect)) {

pageSql.append(sql);

pageSql.append(" limit " + page.getCurrentResult() + “,” + page.getShowCount());

} else if (“oracle”.equals(dialect)) {

pageSql.append(“select * from (select tmp_tb.*,ROWNUM row_id from (”);

pageSql.append(sql);

pageSql.append(") tmp_tb where ROWNUM<=");

pageSql.append(page.getCurrentResult() + page.getShowCount());

pageSql.append(") where row_id>");

pageSql.append(page.getCurrentResult());

}

return pageSql.toString();

} else {

return sql;

}

}

public Object plugin(Object arg0) {

// TODO Auto-generated method stub

return Plugin.wrap(arg0, this);

}

public void setProperties(Properties p) {

dialect = p.getProperty(“dialect”);

if (dialect == null || dialect.equals("")) {

try {

throw new PropertyException(“dialect property is not found!”);

} catch (PropertyException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

pageSqlId = p.getProperty(“pageSqlId”);

if (dialect == null || dialect.equals("")) {

try {

throw new PropertyException(“pageSqlId property is not found!”);

} catch (PropertyException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

4、在Configuration.xml中配置插件

注意:这个插件定义了一个规则,也就是在mapper中SQL语句的id必须包含ListPage才能被拦截。否则将不会分页处理。

5、在UserController.java中添加测试的Controller

@RequestMapping("/pagelist")

public ModelAndView pageList(HttpServletRequest request, HttpServletResponse response) {

int currentPage = request.getParameter(“page”) == null ? 1 : Integer.parseInt(request.getParameter(“page”));

int pageSize = 3;

if (currentPage <= 0) {

currentPage = 1;

}

int currentResult = (currentPage - 1) * pageSize;

System.out.println(request.getRequestURI());

System.out.println(request.getQueryString());

PageInfo page = new PageInfo();

page.setShowCount(pageSize);

page.setCurrentResult(currentResult);

List

articles = userMapper.selectArticleListPage(page, 1);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/591636.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号