프로젝트가 시작될 때 Mybatis 페이징을 사용해야했습니다. 온라인으로 많은 플러그인을 읽었습니다. 실제로 구현 원칙은 기본적으로 동일하지만 대부분 코드 만 제공하고 불완전한 주석이 있습니다. 그래서 나는 많은 기사를 언급 한 다음 (각 기사는 작은 코드를 훔치고, 내 자신의 평가를 받고, 반 표식화 한 후) 프로젝트에 적합한 페이징 플러그인을 모방하고 썼습니다. 더 이상 고민하지 않고 코드를 업로드했습니다. 대부분의 기사와 비교할 때 주석은 매우 완전합니다.
가장 중요한 인터셉터
패키지 com.dnkx.interceptor; Java.sql.*; java.util.hashmap import; java.util.properties import; import org.apache.ibatis.executor.resultset.resultsethandler; import org.apache.ibatis.executor.statement.statemandler; import org.apache.ibatis.mapping.boundsql; import org.apache.ibatis.mapping.mappedstatement; org.apache.ibatis.plugin.interceptor import; 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.systemmetaobject; com.dnkx.pojo.page import; /** * * Paging 쿼리가 필요한 작업을 가로 채기 위해 사용되는 Pagination Interceptor. * mybatis 페이징의 원리는 인터셉터를 사용하여 구현됩니다. * JDBC를 사용하여 데이터베이스에서 작동하려면 해당 명령문 객체가 있어야합니다. Mybatis가 SQL 문을 실행하기 전에 SQL 문이 포함 된 명령문 객체를 생성하고 해당 SQL 문*가 문 앞에 생성되므로 문을 생성하기 전에 명령문을 생성하는 데 사용되는 SQL 문으로 시작할 수 있습니다. mybatis에서 명령문은 lourlingstatementhandler 객체의 * 준비 방법에 의해 생성됩니다. 따라서 인터셉터를 사용하여 MyBatis 페이징을 구현하기위한 아이디어 중 하나는 StateHandler 인터페이스의 준비 메소드를 가로 채고 SQL 문을 인터셉터 메소드에서 해당 Pagtination 쿼리 SQL 문으로 변경 한 다음 * StateHandler 객체의 준비 방법을 호출하는 것입니다. * Pagination의 경우 인터셉터에서해야 할 작업 중 하나는 현재 조건을 충족하는 총 레코드 수를 계산하는 것입니다. 이는 원래 SQL 문을 얻고 해당 통계 문으로 변경 한 다음 MyBatis 캡슐화 된 매개 변수 및 설정 * 매개 변수를 사용하여 SQL 문의 매개 변수를 교체하는 것입니다. 그런 다음 레코드 수를 쿼리하는 SQL 문이 실행되어 총 레코드 수를 계산합니다. ** 플러그인에서 사용될 수있는 여러 클래스를 설명합니다.* MetaObject : 속성 값* boundsql을 반환하는 객체를 기반으로 MyBatis가 제공하는 클래스 : SQL을 실행하도록 실행하고 SQL을 실행하는 데 사용되는 매개 변수를 얻을 수 있습니다. mybatis 메모리 페이징. * ParameterAndler : MyBatis에서 SQL에 나타나는 값을 대체하는 데 사용됩니다. * * @Author Li Xiaogui 2016 년 11 월 9 일 10:59:04 */ @Intercepts ({@Signature (type = stationHandler.class, method = "repard", args = {connection.class}), @Signature (type = resultEthandler.class, method = "handleresultsets", args =}))}))})})}) // 페이징 키워드 개인 정적 최종 문자열 select_id = "page"; // 플러그인이 실행하는 코드는 원래 메소드를 대체하고 가장 중요한 인터셉트 @override public object intercept (호출 호출) 던지기 가능 {if (invoction.getTarget () instanceof StatementOf) {// 여기에 쿼리 메소드에 페이지가 포함 된 경우 설정이 있습니다. metaobject metaobject = SystemMetaObject.forObject (StateHandler); MappedStatement MAPPEDSTATEMENT = (MAPPEDSTATEMENT) METAOBJECT.GETVALUE ( "Delegate.MappedStatement"); String selectId = mappedStatement.getId (); String MethodName = selectId.SubString (selectId.lastIndexOf ( ".")+1) .TOLOWERCASE (); // 그런 다음 페이지가 포함되어 있는지 판단하고 if (methorname.contains (select_id)) {boundsql boundsql = (boundsql) metaobject.getValue ( "delegate.boundsql"); // Pagination 매개 변수는 ParameterObject ParameterObject String의 속성입니다. sql = boundsql.getSql (); System.out.println ( "GET SQL :"+SQL); Hashmap <string, object> map = (Hashmap <String, Object>) (boundsql.getParameterObject ()); // page page = (page) (boundsql.getParameterObject ()); 페이지 페이지 = (페이지) map.get ( "page"); // sql string countsql = concatcountsql (sql); 문자열 pagesql = concatpagesql (sql, page); // system.out.println ( "Count SQL을 다시 작성 :"+countsql); System.out.println ( "Select SQL을 다시 작성 :"+pagesql); 연결 연결 = (Connection) invocation.getArgs () [0]; 준비 상태 COUNTSTMT = NULL; resultSet rs = null; int totalcount = 0; try {countstmt = connection.preparestatement (countsql); rs = countstmt.executeQuery (); if (rs.next ()) {totalcount = rs.getint (1); }} catch (sqlexception e) {System.out.println ( "이 예외를 무시"+e); } 마침내 {try {rs.close (); countstmt.close (); } catch (sqlexception e) {System.out.println ( "이 예외 무시"+e); }} metaobject.setValue ( "delegate.boundsql.sql", pagesql); // 바인드 카운트 page.setNumCount (TotalCount); }} return invocation.proceed (); } // StateHandler 유형을 가로 채서 플러그인 메소드를 재정의 @Override public Object Plugin (Object Target) {if (target instanceof statehandler) {return plugin.wrap (target, this); } else {반환 대상; }} @override public void setProperties (속성 속성) {} // enovate sql public string concatcountsql (String SQL) {// StringBuffer sb = new StringBuffer ( "count (*)에서"); /*sql=sql.tolowercase (); if (sql.lastindexof ( "order")> sql.lastindexof ( ")")) {sb.append (sql.substring (sql.indexof ( "from")+4, sql.lastindexof ( "order"))); } else {sb.append (sql.substring (sql.indexof ( "from")+4)); }*/ StringBuffer sb = new StringBuffer (); sql = sql.tolowercase (); if (sql.lastindexof ( "order")> 0) {sql = sql.substring (0, sql.indexof ( "order")); } sb.append ( "select count (*)에서 ("+sql+") tmp"); 반환 sb.toString (); } public String concatpagesql (String SQL, Page Page) {StringBuffer sb = new StringBuffer (); sb.append (SQL); sb.append ( "limit") .append (page.getPageBegin ()). Append ( ",") .append (page.getPagesize ()); 반환 sb.toString (); }} 페이지 클래스 [Java] 평면 CopyPackage com.dnkx.pojo; java.util.hashmap import; java.util.map import; / ** * * Pagination Query 보조 클래스 * @Author Li Xiaogui 2016 년 11 월 9 일 13:55:37 */ 공개 클래스 페이지 { //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- pageCurrentPage;//How many pages are private int pagebegin; // 시작 위치 개인 int numcount; // 개인 int pagetotal의 총 수; // 총 개인 문자열 주문 orderfield = "; // 정렬 페이지에 표시되는 개인 문자열 주문 방향을 제어합니다 =" "; public page () {} public page (int pagesize, int pagecurrentpage) {super (); this.pagesize = pagesize; this.pagecurrentpage = pagecurrentPage; } public page (map <string, string> map) {if (map.get ( "pagenum")! = null) {this.setpagecurrentPage (this.pagecurrentPage = integer.parseint ( "pagenum")); quer}; if (map.get ( "numperpage")! = null) {this.setPagesize (integer.parseint ( "numperpage")); // 페이지 당 표시된 항목의 // num} else.setpagesize (5); // if ( "order ("orderfield ")) } if (map.get ( "orderDirection")! = null) {this.setOrderDirection (map.get ( "OrderDirection")); }} public int getPageCurrentPage () {return pageCurrentPage; } public void setPageCurrentPage (int pageCurrentPage) {this.pagecurrentPage = pageCurrentPage; } public int getNumCount () {return numCount; } public void setNumcount (int numcount) {this.numcount = numcount; } public int getPageTotal () {return (numCount%pagesize> 0)? } public void setpagetotal (int pagetotal) {this.pagetotal = pagetotal; } public int getPagesize () {return pagesize; } public void setPagesize (int pagesize) {this.pagesize = pagesize; } public int getPageBegin () {return pagesize*(pageCurrentPage-1); } public void setpagebegin (int pagebegin) {this.pagebegin = pagebegin; } public String getOrderfield () {return Orderfield; } public void setorderfield (String Orderfield) {this.orderfield = Orderfield; } public String getOrderDirection () {return orderdirection; } public void setOrderDirection (String OrderDirection) {this.OrderDirection = OrderDirection; } public static page getPage (int pagesize, int pagecurrentPage) {return new Page (pagesize, pagecurrentPage); } public static page getPage (맵 맵) {return new Page (맵); }}컨트롤러의 호출 방법
공개 문자열 목록 (httpservletrequest 요청) {long a = system.currenttimeMillis (); HASHMAP <String, Object> Map = getRequestMap.getMap (요청); // 메소드를 직접 캡슐화하고 요청 페이지의 매개 변수를 캡슐화하고 Page.GetPage (Map); // Page Map.put ( "Page", Page); // 페이지 객체를 매개 변수 세트에 사용합니다. map.put (map.get ( "Orderfield")+"", map.get ( "OrderDirection")); 목록 <plineplyee> list = Employepice.getListPage (MAP); request.setattribute ( "emlist", list); request.setAttribute ( "page", page); request.setAttribute ( "지도",지도); // 페이지 관련 속성 가져 오기 페이지.getNumCount (); // 총 페이지 수 page.getPagetotal (); // 총 페이지 수 긴 b = System.CurrentTimeMillis (); System.out.println ( "-------------- 시간 소모 :"+(ba)+"ms"); "Basic/Employee_list"를 반환합니다. }마지막으로 스프링에서 플러그인을 구성하십시오
<bean id = "pageinterctor"> < /bean> <!-Spring and MyBatis는 완벽하게 통합되어 있으며 myBatis 구성 매핑 파일-> <bean id = "sqlsessionFactory"> <property name = "dataSource"ref = "dataSource" /> <!-"dataSource" /> <!-맵핑. value = "classpath : com/dnkx/mapping/*. xml"> </property> <property name = "플러그인"> <ref bean = "pageinterctor"/> </property> </bean>
좋아요, 그게 끝입니다.이 기사는 참조 용입니다! 위대한 하나님의 조언을 기대합니다