Несколько дней назад я поделился внедрением Paging с помощью рукописного запроса на страницу SQL здесь. Теперь давайте посмотрим на использование плагина Mybatis Paging PageHepler для реализации пейджинга.
Причиной использования подключаемого модуля является упрощение написания кода SQL и достичь лучшего физического подкидки, что также может уменьшить ошибки, чем написание полного кода SQL Paging.
Плагин плагина Mybatis Pagin
Я использую реализацию проекта Maven здесь:
1. Сначала импортируйте зависимости плагина Paging:
<dependency> <groupid> com.github.pageHelper </GroupId> <ArtifactId> pageHelper </artifactId> <sersive> 5.0.0 </version> </depertion>
2. Настройте плагин Paging Interceptor
Существует два плагина для перехватчиков страницы конфигурации для официальных документов
1. Настройте плагин Interceptor в конфигурации Mybatis XML
<!- Местоположение плагинов в файле конфигурации должно соответствовать требованиям, в противном случае сообщается об ошибке. Заказ заключается в следующем: Свойства? Interceptor = "com.github.pageHelper.pageInterceptor"> <!-Используйте следующий метод для настройки параметров, и будут представлены все параметры, введенные позже-> <name = "param1" value = "value1"/> </placin> </placins>
2. Настройте плагин Interceptor в файле конфигурации пружины
Используя метод конфигурации атрибута Spring, вы можете использовать атрибут Plugins для его настройки, например, следующее:
<Bean id = "sqlSessionFactory"> <!-Обратите внимание на другие конфигурации-> <name = "plugins"> <Array> <Bean> <name = "свойства"> <!-Настройка параметров с использованием следующего метода, настройте одну строку-> value> params = value1 </value> </propetion> </bean> </arraMe> </bean> </bean> </bean> </bean> </bean> </bean> </bean> </bean> </bean> </bean> </bean> </bean> </bean> </bean>
Здесь я использую второй тип в своем проекте, и параметры в нем настроены в соответствии с фактической ситуацией, или они могут быть настроены без
3. Вызов методов
Заявления SQL -уровня Mapper написаны в соответствии с общим методом запроса, без написания пейджинга:
<!-запрос на страниц-> <select id = "Найдите" refultype = "country"> Select Id, CountryName, CountryCode из Country </select>
Интерфейс слоя Mapper:
/*** Query* @param params* @return*/public list <Country> finds ();
Интерфейс сервисного обслуживания. Интерфейс:
/ ** * Запрос страниц * @param params paragination Параметры Pageno (номер страницы), страницы (количество запросов на страницу) * @return */ public pageinfo <counation> finds (params params);
Класс реализации бизнес -уровня услуг: PageHelper.StartPage (1, 10); Первый параметр указывает, какая страница, а второй параметр указывает количество записей, отображаемых на каждой странице
После выполнения PageHelper.StartPage (1, 10); Заявление, первый метод выбора, сразу же, будет посвящен на стражу: List <Country> blogs = countrymapper.finds ();
Затем используйте PageInfo, чтобы обернуть результаты запроса, PageInfo <Country> pageInfo = new PageInfo <Country> (блоги);
и вернуть PageInfo на контрольный слой
/*** Query*/public pageInfo <Country> находит (params params) // Query int pageno = params.getPageno (); int pageSize = params.getPagesize (); PageHelper.StartPage (Pageno, PageSize); Список <Country> blogs = countrymapper.finds (); // Оберните результат с помощью PageInfo <Country> pageInfo = new PageInfo <Country> (блоги); вернуть PageInfo; }
После возвращения здесь PageInfo передайте параметры Params Pagination и Parse PageInfo на уровне контроллера:
Список <Country> clist = pageInfo.getList (); Затем поместите Clist в объем и используйте <C: Foreach> </c: Foreach> для цикла для получения данных Paging/*** домашней страницы и запроса на страницу* @return*/@requestmapping ("/index") public modelandview index (params params) {modelandview modelandView = new ModelandView (); // сначала первая страница, запрос 10 params.setpageno (1); Params.SetPagesize (10); PageInfo <Country> pageInfo = countryService.finds (params); Список <Country> clist = pageInfo.getList (); // количество запросов длинные couts = countryservice.counts (); modelandview.addobject ("Clist", Clist); modelandview.addobject ("couts", couts); modelandView.setViewName ("index"); return ModelandView; }Вышеуказанное - все коды реализации для ключевых страниц. Теперь посмотрите на коды для всех конфигураций и реализаций:
Pom.xml
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd "> <dolidyversion> 4.0.0 </modelversion> <groupid> com.krry </GroupId> <ratfactid> maven_pagehepler_ora </artifactid> <backaging> war </packaging> <serse> 1,0-spler_ora </artifactid> <cadegaging> War </packaging> <serive> 1,0-spler_ora </artifactid> <cadegaging> war </packaging> 1,0-spler_orar <mame> maven_pageHepler_ora </name> <url> http://maven.apache.org </url> <properties> <project.build.sourceencoding> utf-8 </project.build.sourceEncoding> <!-MyBatis Generator-> <!-Java Intercace и Entity Classering> <!-MyBatis-> <! <TargetJavaproject> $ {basedir}/src/main/java </targetjavaproject> <targetmapperpackage> com.isea533.mybatis.mapper </targetmapperpackage> <TargetModelPackage> com.isea533.mybatis.model </targetmodelpackage>-xml gination. <TargetResourcesProject> $ {basedir}/src/main/resources </targetresourcesproject> <targetxmlpackage> mapper </targetxmlpackage> <!-Compile jdk-версия-> <mybatis. <mapper.version> 3.3.6 </mapper.version> <pagehelper.version> 5.0.0 </pageHelper.version> <mysql.version> 5.1.29 </mysql.version> <spring.version> 4.1.2.release </spring.version> <mybatis.spring.version> 1.2.4 </mybatis.spring.version> </свойства> <Depertiencies> <deyedency> <groupid> junit </GroupId> <strifactid> junit </artifactid> <sersive> 4.11 </version> <cerpope> test </scope> </articed> <bery> <groupd> <group4 <groud4 </group4 </groud <ArtifactId> log4j </artifactid> <sersive> 1.2.17 </version> </dependency> <!-web-> <DepeCted> <groupid> javax.servlet </GroupId> <artifactId> Servlet-API </artifactid> <serse> 2.5 </version> <cerpope> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId> javax.ws.rs </GroupId> <ArtifactId> javax.ws.rs-api </artifactid> <sersive> 2.0 </version> </deploydent> <dehyederies> <groupid> javax.websocket </GroupId> <strifactid> javax.websocket-appi </artifactid> <serse> 1.0 </arvecterence> </arvers> 1.0 </regive> </arverse> </arvectermency> </arbactid> </arbect>. <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.transaction</groupId> <artifactId>javax.transaction-api</artifactId> <version>1.2</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <dependency> <groupId>org.springframework</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <!--spring-oxm dependencies--> <dependency> <groupId>org.codehaus.castor</groupId> <artifactId>castor-xml</artifactId> <version>1.3.3</version> </dependency> <!--spring-json dependency--> <dependency> <groupid> com.fasterxml.jackson.core </GroupId> <ArtifactId> Джексон-Датабинд </artifactId> <sersive> 2.4.2 </version> </dependency> <dehyederince> <groupid> com.fasterxml.jackson.dataformat </GroupD> <pretifactid> artifactid> artifactid> artifactid> artifactid> artifactid> artifactid> artifactid> artifactid> artifactid> artifactid> artifactid>. <sersion> 2.4.2 </version> </dependency> <!-Spring-Aop Depertion-> <Degency> <groupid> org.aspectj </GroupId> <ratifactId> AmposeJWeaver </artifactId> <sersive> 1.8.2 </version> </depecture> <!-Файл загрузки-> <Deploydency> <groupD> </version-filepload </dependency> <!-Загрузка-> <Deploydency> <groupD> </grapplPload </vehyed> <! <ArtifactId> commons-fileUpload </artifactid> <sersive> 1.3.1 </version> </deperency> <!-MySQL-> <Depodency> <groupid> mySQL </GroupId> <artifactid> mysql-connector-java </artifactid> <sersion> $ {mysql.version} </verse> </artifactid>-$ {mysql.version} </verse> </artifactid> <depervice> <groupid> com.alibaba </GroupId> <ArtifactId> druid </artifactid> <sersive> 1.0.11 </version> </dependency> <!-mybatis-> <dehybehid> <groupid> org.mybatis </GroupD> <ratifactid> mybatis </artifactid> <версии> $ {mybatis> $ {mybatis> $ {mybatis> $ {mybatis> <serfactid> </artifactid> </Ground> </depervice> <depervice> <groupid> org.mybatis </GroupId> <artifactid> mybatis-spring </artifactid> <sersiod> $ {mybatis.spring.version} </version> </degybatis> <s! <TrifactId> mybatis-Generator-core </artifactid> <sersion> 1.3.2 </version> <cracpe> compile </scope> <ploication> true </optunal> </depervice> <!-Page Plugin-> <dependency> <groupid> com.github.pagehelper </GroupD> <ratifactid> pageHelper </artifactId> pageHelper </ratifactid> pagehelper <sersion> $ {pageHelper.version} </version> </deperency> <!-General Mapper-> <Dependency> <groupId> tk.mybatis </GroupId> <strifactid> mapper </artifactid> <sersive> $ {mapper.version} </ression> </regement> <grade> <Artifactid> commons-lang3 </artifactid> <sersive> 3.3.2 </version> </dependency> </degifactid> <deyedendentmanagement> <dependencies> <dehyedency> <groupid> org.springframework </GroupId> <StrifactId> spring-framework-bom </artifactid> <serse> $ ably. <cracpe> import </scope> </veyseycy> </vehyederiation> </deperency> </dependencymanagement> <Repositories> <perpository> <id> nexus </id> <mame> локальный частный nexus </name> <url> http://maven.schina.net/content/groups/public/ </maven.oschina.net/content/groups/public/ </maven.oschina.net/content/groups/public/ </uraves> inamedseS> </leleases> <ponphots> <NABLADED> FALSE </enabled> </snapshots> </repository> <perpository> <id> sonatype-nexus-releases </id> <mame> sonatype nexus leveses </name> <url> http://oss.sonatype.org/contents/repositories/urlelees> http://oss.sonatype.orge <leleases> <Nabled> true </enabled> </leleases> <Spanshots> <Nabled> false </inabled> </sposhots> </Repository> <perpository> <id> Sonatype-nexus-snapshots </id> <mame> sonatype nexus snapshots </name>> <URL> http://oss.sonatype.org/content/repositories/snapshots </url> <leleases> <Nabled> false </inabled> </lepeses> <slipshots> <NERADED> true </enabled> </snapshots> </repository> </repository> </repository> </repository> </repository> </repository> </repository> </repository> </repository> </repository> </repository> </repository> </repository> </repository> </repository> <groupId> org.apache.maven.plugins </GroupId> <artifactid> maven-compiler-plugin </artifactid> <serse> 3.2 </version> <configuration> <source> 1.7 </source> <Target> 1.7 </target> </configuration> </plugin> </plugins> </build> </project>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: aop = "http://www.springframework.org/schema/aop" xmlns: context = "http://www.springframework.org/schema/tx" xmlns: util = "http://www.springframe.orshema. xmlns: p = "http://www.springframework.org/schema/p" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.spramework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/Util http://www.springframework.org/schema/Util/spring-ut.0.xsdrame сканирование-> <Контекст: компонент-сканирование base-package = "com.krry"> < /context: component-scan> <!-Импорт внешних ресурсов-> <Контекст: Property Placeholder location = "classpath: jdbc.properties" /> <!-Настройка Druid Data Source-> <Bean Id = DataSource "init-method =" name = "DriverClassName" value = "$ {db.driver}" /> <name = "url" value = "$ {db.url}" /> <name = "username" value = "$ {db.username}" /> <property name = "password" value = "$ {db.password}" /> < /> <bean>-bean>-bean>-bean> < /> <bean> < /> <bean> < /> <bean> < /> <bean> < /> <bean> <! id="txMgr" > <property name="dataSource" ref="dataSource"></property> </bean> <!-- Enable the transaction annotation driver --> <tx:annotation-driven transaction-manager="txMgr" /> <!-- Configure mybatis' sqlSessionFactory --> <bean id="sqlSessionFactory"> <property name="dataSource" ref = "dataSource"/> <name = "configlocation" value = "classPath: mybatis-config.xml"> </property> <name = "typealiasEspackage" value = "com.krry.entity"/> <name = "plugins"> <stray> <Bean> <!-Конфигурация здесь основной демонстрирует, как использовать его. Если вы этого не понимаете, вы должны удалить следующую конфигурацию-> <name = "свойства"> <dall> </value> </property> </bean> </array> </property> </bean> <!-Конфигурация может сканировать сканер, который может сканировать карту в целом-> <Bean> <! value = "com.krry.mapper"> </property> <name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory"> </property> </beans>mybatis-config.xml
<? xml version = "1.0" Encoding = "UTF-8"?> <! Конфигурация doctype public "-// mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <perience> name = "cacheenabled" value = "true" /> <!-отключить мгновенную загрузку связанного объекта для производительности-> <настройка name = "lazyloadingenabled" value = "true" /> <!-Установите форму загрузки связанного объекта. Вот поле нагрузки по требованию (поле загрузки определено SQL). Все поля соответствующей таблицы не будут загружены для улучшения производительности-> <Настройка name = "AggeressiveLazying" value = "false" /> <!-для неизвестных запросов SQL, различные наборы результатов могут быть возвращены для достижения общего эффекта-> <настройка name = "Multiplestestestabledabled" value = "true" /> <! Разрешить использование колонны вместо названия столбцов-> <TrabLemable " /> <! value="true" /> <!-- Allow to use custom primary key values (such as UUID 32-bit encoding generated by the program as key values), and the PK generation strategy of the data table will be overwritten --> <setting name="useGeneratedKeys" value="true" /> <!-- Give nested resultMap support for field-attribute mapping --> <setting name="autoMappingBehavior" value="FULL" /> <!-Cache SQL для операций с обновлением пакетного обновления для повышения производительности-> <Настройка name = "defaultexeCutortype" value = "pacator" /> <!-тайм-аут, если база данных не ответила более 25 000 секунд-> <Настройка name = "defaultStatementtimeout" value = "25" /> <Установка = "LazyLoadTriggerMethods" value = "equals, clone, hashcode, tostring"/> </settings> <typealias> <!-псевдоним для пользовательского объекта-> <!-<typealias type = "com.krry.mybatis.sysmanage.entity.user" alias = "user"/>-> <!-определение паттерного определения-> <comee. </конфигурация>
Springmvc.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: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/util" xmlns: mvc = "http://www.springframe.orgema.orgema. xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.spramework.org/schema/context http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-Включите также драйвер режима аннотации-> <bean/> <! FormattingConversionserseSceactorybean-> <MVC: Annotation-Riven> <MVC: Сообщения-конвертерс-регистрации defaults = "true"> <bean> <name = "Поддержкамедедиатип"> <Situle> <value> text/plain; charset = utf-8 </value> <dute> properation> html; warse = utf-8 </value> </value> <datter> <dute> <dute/html; warset = utf-8 </value> <dute> <dather> <dather> <dathed> <dutemytypes> <ductedmatepes> <dutementhytypes> <dute/html; <bean/> <bean/> <bean> <bean> <свойство name = "prefixjson" value = "false"/> <name = "objectmapper"> <bean> <!-Обработка типа даты в образе ответа-> <свойство имя = "dateformat"> <bean> <constructor-Arge = "java.lang.string" /> </bean> </property> <!-Не отображается, когда поле null-> <property name = "serializationinclusion"> <value type = "com.fasterxml.jackson.annotation.jsoninclude.include"> non_null </value> </property> </bean> </property> <properation = "no_null </value> </property> </bean> </property> <property =". <dute> application/json; charset = utf-8 </value> <datter> application/xwww-form-urlencoded; charset = utf-8 </value> </list> </property> </bean> </mvc: compert-conterters> </mvc: аннотация> <! base-package = "com.krry.controller"> </context: component-scan> <!-Доступ к статическим файлам ресурсов должен быть установлен, потому что в конфигурации Springmvc все запросы (.do, Adduser, JS/Image/CSS) в этом проекте будут профинансированы SpringMVC, и все файлы STATIC должны быть FiLTERED-FILTERE и выпущенные. Фильтрация-> <!-<mvc: по умолчанию-спертлету-handler //>-> <mvc: farounds mapping = "/resource/**" location = "/resource/"/> <!-View rendering JSP/FreeMaker/Velocity-> <Bean> <!-Создать путь к хранилищу страницы-> <свойство = "prefix" value = "/web-in vage/" web-in Суффикс-> <name = name = "Суффикс" value = ". jsp"> </property> </beans>
jdbc.properties и log4j.properties не нужно отображать, они почти одинаковы
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 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd". <SIVEL-name> MAVEN_PAGEHEPLER </display-name> <selcownfile-file-list> <selcoven-file> index/index </werving-file> </werveding-file-list> <context-param> <param-name> contextconfiglocation </param-name> <param-Value> classPath: ApplicationContext.xml </param-value> </context-param> classpath: applicateContext.xml </param-value> </context-par <lloader-class> org.springframework.web.context.contextloaderListener </sluster> </sluster> <Learser> <Learser-class> org.springframework.web.util.introspectorcleanuplistener </sluster> </slireder> <filater> <filater-name> encoding> enmoding> aname-name> </railter> </filetter> <filater> name> ename> <filter-class> org.springframework.web.filter.characterencodingfilter </filter-class> <init-param> <param-name> кодирование </param-name> <value> utf-8 </param-value> </init-param> </filter> <filater-mapping> <filater-name> encoding> enaming> ename> enaming> ename> enaming> enaming> enaming> enaming> enaming> enaming> enaming> </init-param> </filter> <filater> <filater-nami <Url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name> maven_pagehepler </servlet-name> <verlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <init-param> <param-name> contextconfiglection </servlet> <init-param> <param-name> contextconfiglocation </servlet> <initparam> <param-name> <param-value> classpath: Springmvc.xml </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name> maven_pagehepler </servlet-name> <url-pattern>/index/index </url-pattern> </servlet-mapping> <servlet-mapping> <servlet> <servlet> <servlet> <Servlet> <Servlet-name> maven_pageHepler </servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Класс сущности: Country.java
пакет com.krry.entity; public class country { / *** Первичный ключ* / private integer id; / *** Имя*/ Private String CountryName; / *** code*/ private String CountryCode; Общественная страна (IDEGER ID, String CountryName, String CountryCode) {this.id = id; this.countryname = countryName; this.countryCode = CountryCode; } / *** Получить первичный ключ** @return id - первичный ключ* / public integer getId () {return id; } / *** Установить первичный ключ** @param ID Первичный ключ* / public void setId (integer id) {this.id = id; } / *** Получить имя** @return countryName - имя* / public String getCountryName () {return CountryName; } / *** Установите имя** @param countryName name* / public void setCountryName (String countryName) {this.countryName = countryName; } / *** Получить код** @return CountryCode - Code* / public String getCountryCode () {return CountryCode; } / *** Установить код** @param CountryCode Code* / public void setCountryCode (String CountryCode) {this.countryCode = countryCode; }}Params.java
пакет com.krry.entity;/** * * params * @author krry * @version 1.0.0 * */public class params {private integer pagesize = 10; частное целое число Pageno = 0; public integer getPageno () {return pageno; } public void SetPageno (Integer pageno) {this.pageno = pageno; } public integer getPagesize () {return PageSize; } public void setPagesize (Integer PageSize) {this.pagesize = pagesize; }} Устойчивый слой: Countrymapper.java
пакет com.krry.mapper; import java.util.list; import com.krry.entity.country;/** * * * Mapper: Operate Database * @author krry * @version 1.0.0 * */public interface countrymapper {/** * query * @param params * @return */public <) fends (); / ** * Рассчитайте * com.krry.dao.admin * Имя метода: countblogs * @author krry * @param params * @return int * @exception * @since 1.0.0 */ public long counts (); } Countrymapper.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"> <mapperspace = "com.kmapper.courmapper.coun. <!-запрос на страниц-> <select id = "Найдите" reculatype = "country"> Select Id, CountryName, CountryCode из Country </select> <!-Запрос количества блогов-> <select id = "counts" outdentype = "long"> select count (*) из страны </select> </selet>
Интерфейс бизнес -уровня:
пакет com.krry.service; импорт java.util.hashmap; import java.util.list; импорт javax.servlet.http.httpservletrequest; импорт org.apache.ibatis.annotations.param; импорт com.github.pagehelper.pageinfo; импорт. com.krry.entity.Params;/** * service layer: handle business logic (implemented in impl) * @author asusaad * */public interface ICountryService { /** * Pagination query for all blogs* @param params pagination parameters pageNo (page number), pageSize (number of queries per page) * @return */ public PageInfo<Country> Находит (Params Params); / ** * Рассчитайте количество блогов * @param params * @return */ public long counts (); } Класс внедрения бизнеса
пакет com.krry.service.impl; import java.util.hashmap; import java.util.list; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereoty.service; import org.spramework.web.servlet.modelype.service; импорт org.spramework.web.servle. com.github.pagehelper.pagehelper; import com.github.pagehelper.pageinfo; import com.krry.entity.country; import com.krry.entity.params; импорт com.krry.mapper.countrymapper; import com.krry.service.icountryser asusaad * */ @servicepublic class class supparyservice реализует icountryservice {@autowired private countrymapper countrymapper; /*** Query*/public pageInfo <Country> finds (params params) {// Query int pageno = params.getPageno (); int pageSize = params.getPagesize (); PageHelper.StartPage (Pageno, PageSize); Список <Country> blogs = countrymapper.finds (); // Обернуть результат с помощью pageInfo pageInfo <Country> pageInfo = new PageInfo <Country> (блоги); вернуть PageInfo; } / ** * Расчет * @param params * @return * / public long counts () {long couts = countrymapper.counts (); вернуть моды; }} Управляющий слой: krrycontroller.java
пакет com.krry.controller; import java.util.arraylist; import java.util.hashmap; import java.util.list; import org.junit.test; import org.springframework.beans.factory.annotation.autowired; import org.spramework.beantoypoty.controller. org.springframework.web.bind.annotation.requestmapping; импорт org.springframework.web.bind.annotation.responsebody; импорт org.springframework.web.servlet.modelandView; импорт com.github.pagehelper.pageinfo; импорт. com.krrry.entity.params; import com.krry.service.icocom. ** * krrycontroller * Уровень контроллера, перенаправленный как запрос * @author asusaad * */ @controller // означает, что он является мульти-вазом, а веб-слои, возвращаемый каждым пользователем @requestmapping ("/index" Icountryservice Supplyservice; /*** Главная страница и запрос на страницу* @return*/@requestmapping ("/index") public modelandview index (params params) {modelandView modelandView = new ModelAndView (); // сначала первая страница, запрос 10 params.setpageno (1); Params.SetPagesize (10); PageInfo <Country> pageInfo = countryService.finds (params); Список <Country> clist = pageInfo.getList (); // количество запросов длинные couts = countryservice.counts (); modelandview.addobject ("Clist", Clist); modelandview.addobject ("couts", couts); modelandView.setViewName ("index"); return ModelandView; }/** * Запрос страниц для запроса ajax * @param params * @return */@responsebody @requestmapping ("/loaddata") public hashmap <String, Object> LoadData (params params) {hashmap <String, Object> Map = new Hashmap <строка, объект> (); PageInfo <Country> pageInfo = countryService.finds (params); Список <Country> clist = pageInfo.getList (); map.put ("Clist", Clist); карта возврата; } //}Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.