欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatis分页效果实现代码

程序员文章站 2024-02-29 22:18:22
本文为大家分享了mybatis分页效果展示的具体代码,供大家参考,具体内容如下 mybatis版本3.4以下 结构: spring-mvc.xml &l...

本文为大家分享了mybatis分页效果展示的具体代码,供大家参考,具体内容如下

mybatis版本3.4以下

结构:

mybatis分页效果实现代码

spring-mvc.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
 xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemalocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 自动扫描加载注解的包 -->
<context:component-scan base-package="com.ij34.bean"/>
<bean id="viewresolver" class="org.springframework.web.servlet.view.internalresourceviewresolver"> 
<property name="prefix" value="/web-inf/view/"></property>
<property name="suffix" value=".jsp" ></property>
</bean>

</beans>

com.ij34.mybatis

applicationcontext.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemalocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.3.xsd"
   default-autowire="byname" default-lazy-init="false"> 
 <!-- showcase's customfreemarkermanager example -->
 <bean id="datasource" class="org.apache.commons.dbcp2.basicdatasource">
  <property name="driverclassname" value="com.mysql.jdbc.driver"></property> 
  <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property> 
  <property name="username" value="root"></property> 
  <property name="password" value="123456"></property> 
 </bean> 
 <bean id="transactionmanager" class="org.springframework.jdbc.datasource.datasourcetransactionmanager">
  <property name="datasource" ref="datasource" />
 </bean>
 <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">
  <property name="datasource" ref="datasource"></property>
  <property name="configlocation" value="classpath:com/ij34/mybatis/mybatis-config.xml"></property>
  <property name="mapperlocations" value="classpath:com/ij34/mybatis/usermapper.xml"></property>
 </bean>
<bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">
 <property name="basepackage" value="com.ij34.model"></property>
 <property name="sqlsessionfactory" ref="sqlsessionfactory" /> 
</bean>
</beans>

mybatis-config.xml

<?xml version="1.0" encoding="utf-8" ?>
<!doctype configuration
 public "-//mybatis.org//dtd config 3.0//en"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typealiases>
<typealias type="com.ij34.model.article" alias="article"/>
<typealias type="com.ij34.model.user" alias="user"/>
<typealias type="com.ij34.pages.pageinfo" alias="pageinfo"/>
</typealiases>
 <plugins>
  <plugin interceptor="com.ij34.pages.pageplugin">
   <property name="dialect" value="mysql" />
   <property name="pagesqlid" value=".*listpage.*" />
  </plugin>
 </plugins>
</configuration>

usermapper.xml

<?xml version="1.0" encoding="utf-8" ?>
<!doctype mapper
 public "-//mybatis.org//dtd mapper 3.0//en"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 <mapper namespace="com.ij34.model.usermapper">
<resultmap type="article" id="resultaticlelist">
 <id property="id" column="aid"/>
 <result property="title" column="title"/>
 <result property="content" column="content"/>
 <association property="user" javatype="user">
 <id property="id" column="id"/>
 <result property="name" column="name"/>
 <result property="age" column="age"/>
 </association>
 </resultmap>
 <select id="selectarticle" parametertype="int" resultmap="resultaticlelist">
 select users.id,users.name,users.age,article.id aid,article.title,article.content from users,article
 where users.id=article.userid and users.id=#{id}
 </select>
 
 <select id="listpage" resultmap="resultaticlelist">
 select users.id,users.name,users.age,article.id aid,article.title,article.content from users,article
 where users.id=article.userid and users.id=#{userid}
 </select>
 
 </mapper>

com.ij34.model

user.java

package com.ij34.model;

public class user {
 private int id;
 private string name;
 private int age;


 public int getid() {
 return id;
}

public void setid(int id) {
 this.id = id;
}

public string getname() {
 return name;
}

public void setname(string name) {
 this.name = name;
}

public int getage() {
 return age;
}

public void setage(int age) {
 this.age = age;
}
public string tostring() {
 return "user [id=" + id + ", name=" + name + ", age=" + age + "]";
}


}

article.java

package com.ij34.model;

public class article {
 private int id;
 private user user;
 private string title;
 private string content;
 
public string getcontent() {
 return content;
}
public void setcontent(string content) {
 this.content = content;
}
public int getid() {
 return id;
}
public void setid(int id) {
 this.id = id;
}
public user getuser() {
 return user;
}
public void setuser(user user) {
 this.user = user;
}
public string gettitle() {
 return title;
}
public void settitle(string title) {
 this.title = title;
}

 
}

usermapper.java

package com.ij34.model;

import java.util.list;

import org.apache.ibatis.annotations.param;

import com.ij34.pages.pageinfo;

public interface usermapper {
  
 public list<article> selectarticle(int id); 
 public list<article> listpage(@param("page") pageinfo page,@param("userid") int userid);
}

com.ij34.pages

参考网上的分页插件

pageinfo.java

package com.ij34.pages;

import java.io.serializable;

public class pageinfo implements serializable {

 private static final long serialversionuid = 587754556498974978l;
 
 //pagesize ,每一页显示多少
 private int showcount = 9;
 //总页数
 private int totalpage;
 //总记录数
 private int totalresult;
 //当前页数
 private int currentpage;
 //当前显示到的id, 在mysql limit 中就是第一个参数.
 private int currentresult;
 private string sortfield;
 private string order;
 
 
 public int getshowcount() {
  return showcount;
 }
 public void setshowcount(int showcount) {
  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;
 }
 
 
}

pageplugin.java

@intercepts({ @signature(type = statementhandler.class, method = "prepare", args = { connection.class }) })

要用3.4以下版本,可以参考官方

package com.ij34.pages;

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.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.scripting.xmltags.foreachsqlnode;
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 }) })
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("总数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<string, object> map = (map<string, object>)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<parametermapping> 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();
   }
  }
 }


}

reflecthelper.java

package com.ij34.pages;

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); 
  } 
 } 

}

com.ij34.bean 

package com.ij34.bean;

import java.util.list;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.servlet.modelandview;

import com.ij34.model.*;
import com.ij34.pages.pageinfo;

@controller
@requestmapping("/article")
public class test {
 @autowired
 usermapper mapper;

 @requestmapping("/list")
 public modelandview listall(httpservletrequest request,httpservletresponse response){
  list<article> articles=mapper.selectarticle(1);
  //制定视图,也就是list.jsp
  modelandview mav=new modelandview("list");
  mav.addobject("articles",articles);
  return mav;
 }
 

 @requestmapping("/pagelist")
 public modelandview pagelist(httpservletrequest request,httpservletresponse response){
  int currentpage = request.getparameter("page")==null?1:integer.parseint(request.getparameter("page"));
  int pagesize = 9;
  if (currentpage<=1){
   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<article> articles=mapper.listpage(page,1);
  
  system.out.println(page);
  
  int totalcount = page.gettotalresult();
  
  int lastpage=0;
  if (totalcount % pagesize==0){
   lastpage = totalcount % pagesize;
  }
  else{
   lastpage =1+ totalcount / pagesize;
  }
  
  if (currentpage>=lastpage){
   currentpage =lastpage;
  }
  
  string pagestr = "";
  pagestr=string.format("<a href=\"%s\">上一页</a>    <a href=\"%s\">下一页</a>",
      request.getrequesturi()+"?page="+(currentpage-1),request.getrequesturi()+"?page="+(currentpage+1) );

  //制定视图,也就是list.jsp
  modelandview mav=new modelandview("list");
  mav.addobject("articles",articles);
  mav.addobject("pagestr",pagestr);
  return mav;
 }
/* public modelandview show(){//@requestparam 请求参数 
  list<article> articles=mapper.selectarticle(1);
  modelandview mav=new modelandview("list");
  mav.addobject("articles", articles);
 return mav;
 
 }*/
}

webcontent

web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="webapp_id" version="2.5">
 <display-name>mybatis_springmvc</display-name>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
 <context-param>
 <param-name>contextconfiglocation</param-name>
 <param-value>classpath:com/ij34/mybatis/applicationcontext.xml</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
 </listener>
 <listener>
 <listener-class>
   org.springframework.web.context.contextcleanuplistener</listener-class>
 </listener>
 <servlet>
 <servlet-name>springdispatcherservlet</servlet-name>
 <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
 <init-param>
  <param-name>contextconfiglocation</param-name>
  <param-value>classpath:spring-mvc.xml</param-value>
 </init-param>
 </servlet>
 <servlet-mapping>
 <servlet-name>springdispatcherservlet</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
 <filter>
 <filter-name>characterencodingfilter</filter-name>
 <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class>
 <init-param>
  <param-name>encoding</param-name>
  <param-value>utf8</param-value>
 </init-param>
 <init-param>
  <param-name>forceencoding</param-name>
  <param-value>true</param-value>
 </init-param>
 </filter>
 <filter-mapping>
 <filter-name>characterencodingfilter</filter-name>
 <url-pattern>*</url-pattern>
 </filter-mapping>
</web-app>
 

index.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8"
 pageencoding="utf-8"%>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
</head>
<body>
 <a href="article/list" rel="external nofollow" >不分页测试</a><br /><p />
 <a href="article/pagelist" rel="external nofollow" >分页测试</a>
</body>
</html>

list.jsp

<%@ page language="java" contenttype="text/html; charset=utf-8"
 pageencoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
</head>
<body>
<table>
<c:foreach var="article" items="${articles}">
<tr><td>${article.id} |</td><td> ${article.title}|</td><td> ${article.content}|</td><td>${article.user}</td> </tr> 
</c:foreach>
</table>
<h4>${pagestr}</h4>
</body>
</html>


结果

mybatis分页效果实现代码

mybatis分页效果实现代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。