Mybatis經常使用分頁插件完成疾速分頁處置技能。本站提示廣大學習愛好者:(Mybatis經常使用分頁插件完成疾速分頁處置技能)文章只能為提供參考,不一定能成為您想要的結果。以下是Mybatis經常使用分頁插件完成疾速分頁處置技能正文
在未分享全部查詢分頁的履行代碼之前,先懂得一下履行流程。
1.整體上是應用mybatis的插件攔阻器,在sql履行之前攔阻,為查詢語句加上limit X X
2.用一個Page對象,貫串全部履行流程,這個Page對象須要用Java編寫前端分頁組件
3.用一套比擬完全的三層entity,dao,service支撐這個分頁架構
4.這個分頁用到的一些幫助類
注:分享的內容較多,這邊的話我就不把須要的jar逐個羅列,年夜家應用這個分頁功效的時刻缺乏甚麼就去早晨找甚麼jar包便可,盡量用maven包導入由於maven能削減版本抵觸等比擬好的優勢。
我只能說盡量讓年夜家疾速應用這個比擬好用的分頁功效,假如講得不明確,迎接加我QQ一路商量1063150576,。莫噴哈!還有就是文章篇幅能夠會比擬年夜,不外花點時光,把它看完並理論一下必定會收成很多。
第一步:既然主題是環繞怎樣停止分頁的,我們就從mybatis動手,起首,我們把mybatis相干的兩個比擬主要的設置裝備擺設文件拿出來做扼要的懂得,一個是mybatis-config.xml,別的一個是實體所對應的mapper設置裝備擺設文件,我會在設置裝備擺設文件上寫好正文,年夜家一看就會明確。
mybatis-config.xml
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 全局參數 --> <settings> <!-- 使全局的映照器啟用或禁用緩存。 --> <setting name="cacheEnabled" value="false"/> <!-- 全局啟用或禁用延遲加載。當禁用時,一切聯系關系對象都邑即時加載。 --> <setting name="lazyLoadingEnabled" value="true"/> <!-- 當啟用時,有延遲加載屬性的對象在被挪用時將會完整加載隨意率性屬性。不然,每種屬性將會按須要加載。 --> <setting name="aggressiveLazyLoading" value="true"/> <!-- 能否許可單條sql 前往多個數據集 (取決於驅動的兼容性) default:true --> <setting name="multipleResultSetsEnabled" value="true"/> <!-- 能否可使用列的別號 (取決於驅動的兼容性) default:true --> <setting name="useColumnLabel" value="true"/> <!-- 許可JDBC 生成主鍵。須要驅動器支撐。假如設為了true,這個設置將強迫應用被生成的主鍵,有一些驅動器不兼容不外依然可以履行。 default:false --> <setting name="useGeneratedKeys" value="false"/> <!-- 指定 MyBatis 若何主動映照 數據基表的列 NONE:不影射 PARTIAL:部門 FULL:全體 --> <setting name="autoMappingBehavior" value="PARTIAL"/> <!-- 這是默許的履行類型 (SIMPLE: 簡略; REUSE: 履行器能夠反復應用prepared statements語句;BATCH: 履行器可以反復履行語句和批量更新) --> <setting name="defaultExecutorType" value="SIMPLE"/> <!-- 應用駝峰定名法轉換字段。 --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 設置當地緩存規模 session:就會稀有據的同享 statement:語句規模 (如許就不會稀有據的同享 ) defalut:session --> <setting name="localCacheScope" value="SESSION"/> <!-- 設置但JDBC類型為空時,某些驅動法式 要指定值,default:OTHER,拔出空值時不須要指定類型 --> <setting name="jdbcTypeForNull" value="NULL"/> <setting name="logPrefix" value="dao."/> </settings> <!--別號是一個較短的Java 類型的稱號 --> <typeAliases> <typeAlias type="com.store.base.model.StoreUser" alias="User"></typeAlias> <typeAlias type="com.store.base.secondmodel.pratice.model.Product" alias="Product"></typeAlias> <typeAlias type="com.store.base.secondmodel.base.Page" alias="Page"></typeAlias> </typeAliases> <!-- 插件設置裝備擺設,這邊為mybatis設置裝備擺設分頁攔阻器,這個分頁攔阻器須要我們本身完成 --> <plugins> <plugin interceptor="com.store.base.secondmodel.base.pageinterceptor.PaginationInterceptor" /> </plugins> </configuration>
一個ProductMapper.xml作為測試對象,這個mapper文件就簡略設置裝備擺設一個須要用到的查詢語句
<?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.store.base.secondmodel.pratice.dao.ProductDao" > <sql id="baseColumns" > id, product_name as productName, product_no as productNo, price as price </sql> <select id="findList" resultType="com.store.base.secondmodel.pratice.model.Product"> select <include refid="baseColumns"/> from t_store_product </select> </mapper>
第二步:接下去重要針對這個分頁攔阻器停止深刻剖析進修,重要有以下幾個類和其對應接口
(1)BaseInterceptor 攔阻器基本類
(2)PaginationInterceptor 我們要應用的分頁插件類,繼續下面基本類
(3)SQLHelper 重要是用來提早履行count語句,還有就是獲得全部完全的分頁語句
(4)Dialect,MysqlDialect,重要用來數據庫能否支撐limit語句,然後封裝完全limit語句
以下是這幾個類的分享展現
BaseInterceptor.java
package com.store.base.secondmodel.base.pageinterceptor; import java.io.Serializable; import java.util.Properties; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import org.apache.ibatis.plugin.Interceptor; import com.store.base.secondmodel.base.Global; import com.store.base.secondmodel.base.Page; import com.store.base.secondmodel.base.dialect.Dialect; import com.store.base.secondmodel.base.dialect.MySQLDialect; import com.store.base.util.Reflections; /** * Mybatis分頁攔阻器基類 * @author yiyong_wu * */ public abstract class BaseInterceptor implements Interceptor, Serializable { private static final long serialVersionUID = 1L; protected static final String PAGE = "page"; protected static final String DELEGATE = "delegate"; protected static final String MAPPED_STATEMENT = "mappedStatement"; protected Log log = LogFactory.getLog(this.getClass()); protected Dialect DIALECT; /** * 對參數停止轉換和檢討 * @param parameterObject 參數對象 * @param page 分頁對象 * @return 分頁對象 * @throws NoSuchFieldException 沒法找到參數 */ @SuppressWarnings("unchecked") protected static Page<Object> convertParameter(Object parameterObject, Page<Object> page) { try{ if (parameterObject instanceof Page) { return (Page<Object>) parameterObject; } else { return (Page<Object>)Reflections.getFieldValue(parameterObject, PAGE); } }catch (Exception e) { return null; } } /** * 設置屬性,支撐自界說方言類和制訂數據庫的方法 * <code>dialectClass</code>,自界說方言類。可以不設置裝備擺設這項 * <ode>dbms</ode> 數據庫類型,插件支撐的數據庫 * <code>sqlPattern</code> 須要攔阻的SQL ID * @param p 屬性 */ protected void initProperties(Properties p) { Dialect dialect = null; String dbType = Global.getConfig("jdbc.type"); if("mysql".equals(dbType)){ dialect = new MySQLDialect(); } if (dialect == null) { throw new RuntimeException("mybatis dialect error."); } DIALECT = dialect; } }
PaginationInterceptor.java
package com.store.base.secondmodel.base.pageinterceptor; import java.util.Properties; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlSource; 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.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import com.store.base.secondmodel.base.Page; import com.store.base.secondmodel.base.util.StringUtils; import com.store.base.util.Reflections; /** * 數據庫分頁插件,只攔阻查詢語句. * @author yiyong_wu * */ @Intercepts({ @Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class }) }) public class PaginationInterceptor extends BaseInterceptor { private static final long serialVersionUID = 1L; @Override public Object intercept(Invocation invocation) throws Throwable { final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; Object parameter = invocation.getArgs()[1]; BoundSql boundSql = mappedStatement.getBoundSql(parameter); Object parameterObject = boundSql.getParameterObject(); // 獲得分頁參數對象 Page<Object> page = null; if (parameterObject != null) { page = convertParameter(parameterObject, page); } // 假如設置了分頁對象,則停止分頁 if (page != null && page.getPageSize() != -1) { if (StringUtils.isBlank(boundSql.getSql())) { return null; } String originalSql = boundSql.getSql().trim(); // 獲得總記載數 page.setCount(SQLHelper.getCount(originalSql, null,mappedStatement, parameterObject, boundSql, log)); // 分頁查詢 當地化對象 修正數據庫留意修正完成 String pageSql = SQLHelper.generatePageSql(originalSql, page,DIALECT); invocation.getArgs()[2] = new RowBounds(RowBounds.NO_ROW_OFFSET,RowBounds.NO_ROW_LIMIT); BoundSql newBoundSql = new BoundSql( mappedStatement.getConfiguration(), pageSql, boundSql.getParameterMappings(), boundSql.getParameterObject()); // 處理MyBatis 分頁foreach 參數掉效 start if (Reflections.getFieldValue(boundSql, "metaParameters") != null) { MetaObject mo = (MetaObject) Reflections.getFieldValue( boundSql, "metaParameters"); Reflections.setFieldValue(newBoundSql, "metaParameters", mo); } // 處理MyBatis 分頁foreach 參數掉效 end MappedStatement newMs = copyFromMappedStatement(mappedStatement,new BoundSqlSqlSource(newBoundSql)); invocation.getArgs()[0] = newMs; } return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { super.initProperties(properties); } private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) { MappedStatement.Builder builder = new MappedStatement.Builder( ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType()); builder.resource(ms.getResource()); builder.fetchSize(ms.getFetchSize()); builder.statementType(ms.getStatementType()); builder.keyGenerator(ms.getKeyGenerator()); if (ms.getKeyProperties() != null) { for (String keyProperty : ms.getKeyProperties()) { builder.keyProperty(keyProperty); } } builder.timeout(ms.getTimeout()); builder.parameterMap(ms.getParameterMap()); builder.resultMaps(ms.getResultMaps()); builder.cache(ms.getCache()); return builder.build(); } public static class BoundSqlSqlSource implements SqlSource { BoundSql boundSql; public BoundSqlSqlSource(BoundSql boundSql) { this.boundSql = boundSql; } @Override public BoundSql getBoundSql(Object parameterObject) { return boundSql; } } }
SQLHelper.java
package com.store.base.secondmodel.base.pageinterceptor; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.ibatis.executor.ErrorContext; import org.apache.ibatis.executor.ExecutorException; import org.apache.ibatis.logging.Log; 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.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; import com.store.base.secondmodel.base.Global; import com.store.base.secondmodel.base.Page; import com.store.base.secondmodel.base.dialect.Dialect; import com.store.base.secondmodel.base.util.StringUtils; import com.store.base.util.Reflections; /** * SQL對象類 * @author yiyong_wu * */ public class SQLHelper { /** * 默許公有結構函數 */ private SQLHelper() { } /** * 對SQL參數(?)設值,參考org.apache.ibatis.executor.parameter.DefaultParameterHandler * * @param ps 表現預編譯的 SQL 語句的對象。 * @param mappedStatement MappedStatement * @param boundSql SQL * @param parameterObject 參數對象 * @throws java.sql.SQLException 數據庫異常 */ @SuppressWarnings("unchecked") public static 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); } @SuppressWarnings("rawtypes") 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()); } } } } /** * 查詢總記載數 * @param sql SQL語句 * @param connection 數據庫銜接 * @param mappedStatement mapped * @param parameterObject 參數 * @param boundSql boundSql * @return 總記載數 * @throws SQLException sql查詢毛病 */ public static int getCount(final String sql, final Connection connection, final MappedStatement mappedStatement, final Object parameterObject, final BoundSql boundSql, Log log) throws SQLException { String dbName = Global.getConfig("jdbc.type"); final String countSql; if("oracle".equals(dbName)){ countSql = "select count(1) from (" + sql + ") tmp_count"; }else{ countSql = "select count(1) from (" + removeOrders(sql) + ") tmp_count"; } Connection conn = connection; PreparedStatement ps = null; ResultSet rs = null; try { if (log.isDebugEnabled()) { log.debug("COUNT SQL: " + StringUtils.replaceEach(countSql, new String[]{"\n","\t"}, new String[]{" "," "})); } if (conn == null){ conn = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection(); } ps = conn.prepareStatement(countSql); BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject); //處理MyBatis 分頁foreach 參數掉效 start if (Reflections.getFieldValue(boundSql, "metaParameters") != null) { MetaObject mo = (MetaObject) Reflections.getFieldValue(boundSql, "metaParameters"); Reflections.setFieldValue(countBS, "metaParameters", mo); } //處理MyBatis 分頁foreach 參數掉效 end SQLHelper.setParameters(ps, mappedStatement, countBS, parameterObject); rs = ps.executeQuery(); int count = 0; if (rs.next()) { count = rs.getInt(1); } return count; } finally { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } } } /** * 依據數據庫方言,生成特定的分頁sql * @param sql Mapper中的Sql語句 * @param page 分頁對象 * @param dialect 方言類型 * @return 分頁SQL */ public static String generatePageSql(String sql, Page<Object> page, Dialect dialect) { if (dialect.supportsLimit()) { return dialect.getLimitString(sql, page.getFirstResult(), page.getMaxResults()); } else { return sql; } } /** * 去除qlString的select子句。 * @param hql * @return */ @SuppressWarnings("unused") private static String removeSelect(String qlString){ int beginPos = qlString.toLowerCase().indexOf("from"); return qlString.substring(beginPos); } /** * 去除hql的orderBy子句。 * @param hql * @return */ private static String removeOrders(String qlString) { Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(qlString); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendWordStrment(sb, ""); } m.appendTail(sb); return sb.toString(); } }
Dialect.java 接口
package com.store.base.secondmodel.base.dialect; /** * 相似hibernate的Dialect,但只精簡出分頁部門 * @author yiyong_wu * */ public interface Dialect { /** * 數據庫自己能否支撐分頁以後的分頁查詢方法 * 假如數據庫不支撐的話,則不停止數據庫分頁 * * @return true:支撐以後的分頁查詢方法 */ public boolean supportsLimit(); /** * 將sql轉換為分頁SQL,分離挪用分頁sql * * @param sql SQL語句 * @param offset 開端條數 * @param limit 每頁顯示若干記載條數 * @return 分頁查詢的sql */ public String getLimitString(String sql, int offset, int limit); }
MySQLDialect.java
package com.store.base.secondmodel.base.dialect; /** * Mysql方言的完成 * @author yiyong_wu * */ public class MySQLDialect implements Dialect { @Override public boolean supportsLimit() { return true; } @Override public String getLimitString(String sql, int offset, int limit) { return getLimitString(sql, offset, Integer.toString(offset),Integer.toString(limit)); } /** * 將sql釀成分頁sql語句,供給將offset及limit應用占位符號(placeholder)調換. * <pre> * 如mysql * dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 將前往 * select * from user limit :offset,:limit * </pre> * * @param sql 現實SQL語句 * @param offset 分頁開端記載條數 * @param offsetPlaceholder 分頁開端記載條數-占位符號 * @param limitPlaceholder 分頁記載條數占位符號 * @return 包括占位符的分頁sql */ public String getLimitString(String sql, int offset, String offsetPlaceholder, String limitPlaceholder) { StringBuilder stringBuilder = new StringBuilder(sql); stringBuilder.append(" limit "); if (offset > 0) { stringBuilder.append(offsetPlaceholder).append(",").append(limitPlaceholder); } else { stringBuilder.append(limitPlaceholder); } return stringBuilder.toString(); } }
差不多到這邊曾經把整塊分頁怎樣完成的給分享完了,然則我們還有更主要的義務,想要全部器械跑起來,確定還要有基本任務要做,接下去我們剖析整套Page對象和它所根據的三層架構,照樣用product作為實體停止剖析。一整套三層架構講上去,收成確定又滿滿的。我們順次從entity->dao->service的次序講上去。
起首,針對我們的實體得繼續兩個籠統實體類BaseEntity 與 DataEntity
BaseEntity.java 重要放置Page成員變量,繼續它後便可以每一個實體都具有這個成員變量
package com.store.base.secondmodel.base; import java.io.Serializable; import java.util.Map; import javax.xml.bind.annotation.XmlTransient; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import com.fasterxml.jackson.annotation.JsonIgnore; import com.谷歌.common.collect.Maps; import com.store.base.model.StoreUser; /** * 最頂層的Entity * @author yiyong_wu * * @param <T> */ public abstract class BaseEntity<T> implements Serializable { private static final long serialVersionUID = 1L; /** * 刪除標志(0:正常;1:刪除;2:審核;) */ public static final String DEL_FLAG_NORMAL = "0"; public static final String DEL_FLAG_DELETE = "1"; public static final String DEL_FLAG_AUDIT = "2"; /** * 實體編號(獨一標識) */ protected String id; /** * 以後用戶 */ protected StoreUser currentUser; /** * 以後實體分頁對象 */ protected Page<T> page; /** * 自界說SQL(SQL標識,SQL內容) */ private Map<String, String> sqlMap; public BaseEntity() { } public BaseEntity(String id) { this(); this.id = id; } public String getId() { return id; } public void setId(String id) { this.id = id; } /** * 這個重要針對shiro履行拔出更新的時刻會挪用,獲得以後的用戶 * @return */ @JsonIgnore @XmlTransient public StoreUser getCurrentUser() { if(currentUser == null){ // currentUser = UserUtils.getUser(); } return currentUser; } public void setCurrentUser(StoreUser currentUser) { this.currentUser = currentUser; } @JsonIgnore @XmlTransient public Page<T> getPage() { if (page == null){ page = new Page<>(); } return page; } public Page<T> setPage(Page<T> page) { this.page = page; return page; } @JsonIgnore @XmlTransient public Map<String, String> getSqlMap() { if (sqlMap == null){ sqlMap = Maps.newHashMap(); } return sqlMap; } public void setSqlMap(Map<String, String> sqlMap) { this.sqlMap = sqlMap; } /** * 拔出之前履行辦法,子類完成 */ public abstract void preInsert(); /** * 更新之前履行辦法,子類完成 */ public abstract void preUpdate(); /** * 能否是新記載(默許:false),挪用setIsNewRecord()設置新記載,應用自界說ID。 * 設置為true後強迫履行拔出語句,ID不會主動生成,需從手動傳入。 * @return */ public boolean getIsNewRecord() { return StringUtils.isBlank(getId()); } /** * 全局變量對象 */ @JsonIgnore public Global getGlobal() { return Global.getInstance(); } /** * 獲得數據庫稱號 */ @JsonIgnore public String getDbName(){ return Global.getConfig("jdbc.type"); } @Override public String toString() { return ReflectionToStringBuilder.toString(this); } }
DataEntity.java,重要存儲更新刪除時光,創立用戶,更新用戶,邏輯刪除標記等
package com.store.base.secondmodel.base; import java.util.Date; import org.hibernate.validator.constraints.Length; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.store.base.model.StoreUser; /** * 數據Entity * @author yiyong_wu * * @param <T> */ public abstract class DataEntity<T> extends BaseEntity<T> { private static final long serialVersionUID = 1L; protected StoreUser createBy; // 創立者 protected Date createDate; // 創立日期 protected StoreUser updateBy; // 更新者 protected Date updateDate; // 更新日期 protected String delFlag; // 刪除標志(0:正常;1:刪除;2:審核) public DataEntity() { super(); this.delFlag = DEL_FLAG_NORMAL; } public DataEntity(String id) { super(id); } /** * 拔出之前履行辦法,須要手動挪用 */ @Override public void preInsert() { // 不限制ID為UUID,挪用setIsNewRecord()應用自界說ID // User user = UserUtils.getUser(); // if (StringUtils.isNotBlank(user.getId())) { // this.updateBy = user; // this.createBy = user; // } this.updateDate = new Date(); this.createDate = this.updateDate; } /** * 更新之前履行辦法,須要手動挪用 */ @Override public void preUpdate() { // User user = UserUtils.getUser(); // if (StringUtils.isNotBlank(user.getId())) { // this.updateBy = user; // } this.updateDate = new Date(); } // @JsonIgnore public StoreUser getCreateBy() { return createBy; } public void setCreateBy(StoreUser createBy) { this.createBy = createBy; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } // @JsonIgnore public StoreUser getUpdateBy() { return updateBy; } public void setUpdateBy(StoreUser updateBy) { this.updateBy = updateBy; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } @JsonIgnore @Length(min = 1, max = 1) public String getDelFlag() { return delFlag; } public void setDelFlag(String delFlag) { this.delFlag = delFlag; } }
Product.java 產物類
package com.store.base.secondmodel.pratice.model; import com.store.base.secondmodel.base.DataEntity; /** *產物基本類 *2016年10月11日 *yiyong_wu */ public class Product extends DataEntity<Product>{ private static final long serialVersionUID = 1L; private String productName; private float price; private String productNo; public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getProductNo() { return productNo; } public void setProductNo(String productNo) { this.productNo = productNo; } }
怎樣樣,是否是看到很龐雜的一個實體繼續連關系,不外這有甚麼,越龐雜就會越完全。接上去我就看看dao層,異樣是三層,預備好接收浸禮吧
BaseDao.java 預留接口
package com.store.base.secondmodel.base; /** * 最頂層的DAO接口 * @author yiyong_wu * */ public interface BaseDao { } CrudDao.java 針對增刪改查的一個dao接口層 [java] view plain copy print?在CODE上檢查代碼片派生到我的代碼片 package com.store.base.secondmodel.base; import java.util.List; /** * 界說增刪改查的DAO接口 * @author yiyong_wu * * @param <T> */ public interface CrudDao<T> extends BaseDao { /** * 獲得單條數據 * @param id * @return */ public T get(String id); /** * 獲得單條數據 * @param entity * @return */ public T get(T entity); /** * 查詢數據列表,假如須要分頁,請設置分頁對象,如:entity.setPage(new Page<T>()); * @param entity * @return */ public List<T> findList(T entity); /** * 查詢一切數據列表 * @param entity * @return */ public List<T> findAllList(T entity); /** * 查詢一切數據列表 * @see public List<T> findAllList(T entity) * @return public List<T> findAllList(); */ /** * 拔出數據 * @param entity * @return */ public int insert(T entity); /** * 更新數據 * @param entity * @return */ public int update(T entity); /** * 刪除數據(普通為邏輯刪除,更新del_flag字段為1) * @param id * @see public int delete(T entity) * @return */ public int delete(String id); /** * 刪除數據(普通為邏輯刪除,更新del_flag字段為1) * @param entity * @return */ public int delete(T entity); }
ProductDao.java mybatis對應的接口mapper,同時也是dao完成,這邊須要自定一個注解@MyBatisRepository
package com.store.base.secondmodel.pratice.dao; import com.store.base.secondmodel.base.CrudDao; import com.store.base.secondmodel.base.MyBatisRepository; import com.store.base.secondmodel.pratice.model.Product; /** *TODO *2016年10月11日 *yiyong_wu */ @MyBatisRepository public interface ProductDao extends CrudDao<Product>{ }
自界說注解MyBatisRepository.java,跟自界說注解相干,這裡就不做過量的解讀,網上材料一堆
package com.store.base.secondmodel.base; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.ElementType; import org.springframework.stereotype.Component; /** * 標識MyBatis的DAO,便利{@link org.mybatis.spring.mapper.MapperScannerConfigurer}的掃描。 * * 請留意要在spring的設置裝備擺設文件中設置裝備擺設掃描該注解類的設置裝備擺設 * *<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> *<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> *<property name="basePackage" value="com.store.base.secondmodel" /> *<property name="annotationClass" value="com.store.base.secondmodel.base.MyBatisRepository" /> *</bean> * @author yiyong_wu * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Component public @interface MyBatisRepository { String value() default ""; }
留意:跟ProductDao.java接洽比擬年夜的是ProductMapper.xml文件,年夜家可以看到下面誰人設置裝備擺設文件的namespace是指向這個dao的途徑的。
接上去我們就進入最初的service剖析了,一樣照樣三層繼續
BaseService.java
package com.store.base.secondmodel.base; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.transaction.annotation.Transactional; /** * Service的最頂層父類 * @author yiyong_wu * */ @Transactional(readOnly = true) public abstract class BaseService { //日記記載用的 protected Logger logger = LoggerFactory.getLogger(getClass()); }
CrudService.java 增刪改查相干的營業接話柄現
package com.store.base.secondmodel.base; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; /** * 增刪改查Service基類 * @author yiyong_wu * * @param <D> * @param <T> */ public abstract class CrudService<D extends CrudDao<T>, T extends DataEntity<T>> extends BaseService { /** * 耐久層對象 */ @Autowired protected D dao; /** * 獲得單條數據 * @param id * @return */ public T get(String id) { return dao.get(id); } /** * 獲得單條數據 * @param entity * @return */ public T get(T entity) { return dao.get(entity); } /** * 查詢列表數據 * @param entity * @return */ public List<T> findList(T entity) { return dao.findList(entity); } /** * 查詢分頁數據 * @param page 分頁對象 * @param entity * @return */ public Page<T> findPage(Page<T> page, T entity) { entity.setPage(page); page.setList(dao.findList(entity)); return page; } /** * 保留數據(拔出或更新) * @param entity */ @Transactional(readOnly = false) public void save(T entity) { if (entity.getIsNewRecord()){ entity.preInsert(); dao.insert(entity); }else{ entity.preUpdate(); dao.update(entity); } } /** * 刪除數據 * @param entity */ @Transactional(readOnly = false) public void delete(T entity) { dao.delete(entity); } }
ProductService.java,去繼續CrudService接口,留意起注入dao和實體類型的一種形式
package com.store.base.secondmodel.pratice.service; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.store.base.secondmodel.base.CrudService; import com.store.base.secondmodel.pratice.dao.ProductDao; import com.store.base.secondmodel.pratice.model.Product; /** *TODO *2016年10月11日 *yiyong_wu */ @Service @Transactional(readOnly = true) public class ProductService extends CrudService<ProductDao,Product>{ }
我想看到這裡的同志曾經很不耐心了。然則假如你錯過接下去的一段,根本上適才看的就快等於白看了,反動的成功就在後半段,由於全部分頁功效環繞的就是一個Page對象,重磅內容終究要出來了,當你把Page對象填充到適才誰人BaseEntity上的時刻,你會發明一切就完全起來了,空話不多說,Page對象以下
package com.store.base.secondmodel.base; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.annotation.JsonIgnore; import com.store.base.secondmodel.base.util.CookieUtils; import com.store.base.secondmodel.base.util.StringUtils; /** * 分頁類 * @author yiyong_wu * * @param <T> */ public class Page<T> implements Serializable{ private static final long serialVersionUID = 1L; private int pageNo = 1; // 以後頁碼 private int pageSize = Integer.parseInt(Global.getConfig("page.pageSize")); // 頁面年夜小,設置為“-1”表現不停止分頁(分頁有效) private long count;// 總記載數,設置為“-1”表現不查詢總數 private int first;// 首頁索引 private int last;// 尾頁索引 private int prev;// 上一頁索引 private int next;// 下一頁索引 private boolean firstPage;//能否是第一頁 private boolean lastPage;//能否是最初一頁 private int length = 6;// 顯示頁面長度 private int slider = 1;// 前後顯示頁面長度 private List<T> list = new ArrayList<>(); private String orderBy = ""; // 尺度查詢有用, 實例: updatedate desc, name asc private String funcName = "page"; // 設置點擊頁碼挪用的js函數稱號,默許為page,在一頁有多個分頁對象時應用。 private String funcParam = ""; // 函數的附加參數,第三個參數值。 private String message = ""; // 設置提醒新聞,顯示在“共n條”以後 public Page() { this.pageSize = -1; } /** * 結構辦法 * @param request 傳遞 repage 參數,來記住頁碼 * @param response 用於設置 Cookie,記住頁碼 */ public Page(HttpServletRequest request, HttpServletResponse response){ this(request, response, -2); } /** * 結構辦法 * @param request 傳遞 repage 參數,來記住頁碼 * @param response 用於設置 Cookie,記住頁碼 * @param defaultPageSize 默許分頁年夜小,假如傳遞 -1 則為不分頁,前往一切數據 */ public Page(HttpServletRequest request, HttpServletResponse response, int defaultPageSize){ // 設置頁碼參數(傳遞repage參數,來記住頁碼) String no = request.getParameter("pageNo"); if (StringUtils.isNumeric(no)){ CookieUtils.setCookie(response, "pageNo", no); this.setPageNo(Integer.parseInt(no)); }else if (request.getParameter("repage")!=null){ no = CookieUtils.getCookie(request, "pageNo"); if (StringUtils.isNumeric(no)){ this.setPageNo(Integer.parseInt(no)); } } // 設置頁面年夜小參數(傳遞repage參數,來記住頁碼年夜小) String size = request.getParameter("pageSize"); if (StringUtils.isNumeric(size)){ CookieUtils.setCookie(response, "pageSize", size); this.setPageSize(Integer.parseInt(size)); }else if (request.getParameter("repage")!=null){ no = CookieUtils.getCookie(request, "pageSize"); if (StringUtils.isNumeric(size)){ this.setPageSize(Integer.parseInt(size)); } }else if (defaultPageSize != -2){ this.pageSize = defaultPageSize; } // 設置排序參數 String orderBy = request.getParameter("orderBy"); if (StringUtils.isNotBlank(orderBy)){ this.setOrderBy(orderBy); } } /** * 結構辦法 * @param pageNo 以後頁碼 * @param pageSize 分頁年夜小 */ public Page(int pageNo, int pageSize) { this(pageNo, pageSize, 0); } /** * 結構辦法 * @param pageNo 以後頁碼 * @param pageSize 分頁年夜小 * @param count 數據條數 */ public Page(int pageNo, int pageSize, long count) { this(pageNo, pageSize, count, new ArrayList<T>()); } /** * 結構辦法 * @param pageNo 以後頁碼 * @param pageSize 分頁年夜小 * @param count 數據條數 * @param list 本頁數據對象列表 */ public Page(int pageNo, int pageSize, long count, List<T> list) { this.setCount(count); this.setPageNo(pageNo); this.pageSize = pageSize; this.list = list; } /** * 初始化參數 */ public void initialize(){ //1 this.first = 1; this.last = (int)(count / (this.pageSize < 1 ? 20 : this.pageSize) + first - 1); if (this.count % this.pageSize != 0 || this.last == 0) { this.last++; } if (this.last < this.first) { this.last = this.first; } if (this.pageNo <= 1) { this.pageNo = this.first; this.firstPage=true; } if (this.pageNo >= this.last) { this.pageNo = this.last; this.lastPage=true; } if (this.pageNo < this.last - 1) { this.next = this.pageNo + 1; } else { this.next = this.last; } if (this.pageNo > 1) { this.prev = this.pageNo - 1; } else { this.prev = this.first; } //2 if (this.pageNo < this.first) {// 假如以後頁小於首頁 this.pageNo = this.first; } if (this.pageNo > this.last) {// 假如以後頁年夜於尾頁 this.pageNo = this.last; } } /** * 默許輸入以後分頁標簽 * <div class="page">${page}</div> */ @Override public String toString() { StringBuilder sb = new StringBuilder(); if (pageNo == first) {// 假如是首頁 sb.append("<li class=\"disabled\"><a href=\"javascript:\">« 上一頁</a></li>\n"); } else { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+prev+","+pageSize+",'"+funcParam+"');\">« 上一頁</a></li>\n"); } int begin = pageNo - (length / 2); if (begin < first) { begin = first; } int end = begin + length - 1; if (end >= last) { end = last; begin = end - length + 1; if (begin < first) { begin = first; } } if (begin > first) { int i = 0; for (i = first; i < first + slider && i < begin; i++) { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">" + (i + 1 - first) + "</a></li>\n"); } if (i < begin) { sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n"); } } for (int i = begin; i <= end; i++) { if (i == pageNo) { sb.append("<li class=\"active\"><a href=\"javascript:\">" + (i + 1 - first) + "</a></li>\n"); } else { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">" + (i + 1 - first) + "</a></li>\n"); } } if (last - end > slider) { sb.append("<li class=\"disabled\"><a href=\"javascript:\">...</a></li>\n"); end = last - slider; } for (int i = end + 1; i <= last; i++) { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+i+","+pageSize+",'"+funcParam+"');\">" + (i + 1 - first) + "</a></li>\n"); } if (pageNo == last) { sb.append("<li class=\"disabled\"><a href=\"javascript:\">下一頁 »</a></li>\n"); } else { sb.append("<li><a href=\"javascript:\" onclick=\""+funcName+"("+next+","+pageSize+",'"+funcParam+"');\">" + "下一頁 »</a></li>\n"); } return sb.toString(); } /** * 獲得分頁HTML代碼 * @return */ public String getHtml(){ return toString(); } /** * 獲得設置總數 * @return */ public long getCount() { return count; } /** * 設置數據總數 * @param count */ public void setCount(long count) { this.count = count; if (pageSize >= count){ pageNo = 1; } } /** * 獲得以後頁碼 * @return */ public int getPageNo() { return pageNo; } /** * 設置以後頁碼 * @param pageNo */ public void setPageNo(int pageNo) { this.pageNo = pageNo; } /** * 獲得頁面年夜小 * @return */ public int getPageSize() { return pageSize; } /** * 設置頁面年夜小(最年夜500)// > 500 ? 500 : pageSize; * @param pageSize */ public void setPageSize(int pageSize) { this.pageSize = pageSize <= 0 ? 10 : pageSize; } /** * 首頁索引 * @return */ @JsonIgnore public int getFirst() { return first; } /** * 尾頁索引 * @return */ @JsonIgnore public int getLast() { return last; } /** * 獲得頁面總數 * @return getLast(); */ @JsonIgnore public int getTotalPage() { return getLast(); } /** * 能否為第一頁 * @return */ @JsonIgnore public boolean isFirstPage() { return firstPage; } /** * 能否為最初一頁 * @return */ @JsonIgnore public boolean isLastPage() { return lastPage; } /** * 上一頁索引值 * @return */ @JsonIgnore public int getPrev() { if (isFirstPage()) { return pageNo; } else { return pageNo - 1; } } /** * 下一頁索引值 * @return */ @JsonIgnore public int getNext() { if (isLastPage()) { return pageNo; } else { return pageNo + 1; } } /** * 獲得本頁數據對象列表 * @return List<T> */ public List<T> getList() { return list; } /** * 設置本頁數據對象列表 * @param list */ public Page<T> setList(List<T> list) { this.list = list; initialize(); return this; } /** * 獲得查詢排序字符串 * @return */ @JsonIgnore public String getOrderBy() { // SQL過濾,避免注入 String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|" + "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)"; Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); if (sqlPattern.matcher(orderBy).find()) { return ""; } return orderBy; } /** * 設置查詢排序,尺度查詢有用, 實例: updatedate desc, name asc */ public void setOrderBy(String orderBy) { this.orderBy = orderBy; } /** * 獲得點擊頁碼挪用的js函數稱號 * function ${page.funcName}(pageNo){location="${ctx}/list-${category.id}${urlSuffix}?pageNo="+i;} * @return */ @JsonIgnore public String getFuncName() { return funcName; } /** * 設置點擊頁碼挪用的js函數稱號,默許為page,在一頁有多個分頁對象時應用。 * @param funcName 默許為page */ public void setFuncName(String funcName) { this.funcName = funcName; } /** * 獲得分頁函數的附加參數 * @return */ @JsonIgnore public String getFuncParam() { return funcParam; } /** * 設置分頁函數的附加參數 * @return */ public void setFuncParam(String funcParam) { this.funcParam = funcParam; } /** * 設置提醒新聞,顯示在“共n條”以後 * @param message */ public void setMessage(String message) { this.message = message; } /** * 分頁能否有用 * @return this.pageSize==-1 */ @JsonIgnore public boolean isDisabled() { return this.pageSize==-1; } /** * 能否停止總數統計 * @return this.count==-1 */ @JsonIgnore public boolean isNotCount() { return this.count==-1; } /** * 獲得 Hibernate FirstResult */ public int getFirstResult(){ int firstResult = (getPageNo() - 1) * getPageSize(); if (firstResult >= getCount()) { firstResult = 0; } return firstResult; } /** * 獲得 Hibernate MaxResults */ public int getMaxResults(){ return getPageSize(); } }
看完這個Page對象應當略微有點感到了吧,然後我在胡亂貼一些相干用到的對象類吧,對象類的話我只略微提一下,詳細年夜家可以弄到本身的代碼上好好解讀。
PropertiesLoader.java 用來獲得resource文件夾下的常量設置裝備擺設文件
package com.store.base.secondmodel.base.util; import java.io.IOException; import java.io.InputStream; import java.util.NoSuchElementException; import java.util.Properties; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; /** * Properties文件載入對象類. 可載入多個properties文件, * 雷同的屬性在最初載入的文件中的值將會籠罩之前的值,但以System的Property優先. * @author yiyong_wu * */ public class PropertiesLoader { private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class); private static ResourceLoader resourceLoader = new DefaultResourceLoader(); private final Properties properties; public PropertiesLoader(String... resourcesPaths) { properties = loadProperties(resourcesPaths); } public Properties getProperties() { return properties; } /** * 掏出Property,但以System的Property優先,取不到前往空字符串. */ private String getValue(String key) { String systemProperty = System.getProperty(key); if (systemProperty != null) { return systemProperty; } if (properties.containsKey(key)) { return properties.getProperty(key); } return ""; } /** * 掏出String類型的Property,但以System的Property優先,假如都為Null則拋出異常. */ public String getProperty(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return value; } /** * 掏出String類型的Property,但以System的Property優先.假如都為Null則前往Default值. */ public String getProperty(String key, String defaultValue) { String value = getValue(key); return value != null ? value : defaultValue; } /** * 掏出Integer類型的Property,但以System的Property優先.假如都為Null或內容毛病則拋出異常. */ public Integer getInteger(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return Integer.valueOf(value); } /** * 掏出Integer類型的Property,但以System的Property優先.假如都為Null則前往Default值,假如內容毛病則拋出異常 */ public Integer getInteger(String key, Integer defaultValue) { String value = getValue(key); return value != null ? Integer.valueOf(value) : defaultValue; } /** * 掏出Double類型的Property,但以System的Property優先.假如都為Null或內容毛病則拋出異常. */ public Double getDouble(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return Double.valueOf(value); } /** * 掏出Double類型的Property,但以System的Property優先.假如都為Null則前往Default值,假如內容毛病則拋出異常 */ public Double getDouble(String key, Integer defaultValue) { String value = getValue(key); return value != null ? Double.valueOf(value) : defaultValue.doubleValue(); } /** * 掏出Boolean類型的Property,但以System的Property優先.假如都為Null拋出異常,假如內容不是true/false則前往false. */ public Boolean getBoolean(String key) { String value = getValue(key); if (value == null) { throw new NoSuchElementException(); } return Boolean.valueOf(value); } /** * 掏出Boolean類型的Property,但以System的Property優先.假如都為Null則前往Default值,假如內容不為true/false則前往false. */ public Boolean getBoolean(String key, boolean defaultValue) { String value = getValue(key); return value != null ? Boolean.valueOf(value) : defaultValue; } /** * 載入多個文件, 文件途徑應用Spring Resource格局. */ private Properties loadProperties(String... resourcesPaths) { Properties props = new Properties(); for (String location : resourcesPaths) { InputStream is = null; try { Resource resource = resourceLoader.getResource(location); is = resource.getInputStream(); props.load(is); } catch (IOException ex) { logger.error("Could not load properties from path:" + location , ex); } finally { IOUtils.closeQuietly(is); } } return props; } }
Global.java 用來獲得全局的一些常量,可所以從設置裝備擺設文件中讀取的常量,也能夠是界說成final static的常量,獲得設置裝備擺設文件的話是挪用下面誰人類停止獲得的。
package com.store.base.secondmodel.base; import java.io.File; import java.io.IOException; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.DefaultResourceLoader; import com.谷歌.common.collect.Maps; import com.store.base.secondmodel.base.util.PropertiesLoader; import com.store.base.secondmodel.base.util.StringUtils; /** * 全局設置裝備擺設類 * @author yiyong_wu * */ public class Global { private static final Logger logger = LoggerFactory.getLogger(Global.class); /** * 以後對象實例 */ private static Global global = new Global(); /** * 保留全局屬性值 */ private static Map<String, String> map = Maps.newHashMap(); /** * 屬性文件加載對象 */ private static PropertiesLoader loader = new PropertiesLoader("application.properties"); /** * 顯示/隱蔽 public static final String SHOW = "1"; public static final String HIDE = "0"; /** * 是/否 */ public static final String YES = "1"; public static final String NO = "0"; /** * 狀況 上/下 app公用 */ public static final String UPSHVELF = "1"; public static final String DOWNSHVELF = "2"; public static final String SEPARATOR = "/"; /** * 對/錯 */ public static final String TRUE = "true"; public static final String FALSE = "false"; /** * 上傳文件基本虛擬途徑 */ public static final String USERFILES_BASE_URL = "/userfiles/"; /** * 針對富文本編纂器,開頭會發生的空div */ public static final String ENDS = "<p><br></p>"; /** * 默許空的公有結構函數 */ public Global() { //do nothing in this method,just empty } /** * 獲得以後對象實例 */ public static Global getInstance() { return global; } /** * 獲得設置裝備擺設 */ public static String getConfig(String key) { String value = map.get(key); if (value == null){ value = loader.getProperty(key); map.put(key, value != null ? value : StringUtils.EMPTY); } return value; } /** * 獲得URL後綴 */ public static String getUrlSuffix() { return getConfig("urlSuffix"); } /** * 頁面獲得常量 * @see ${fns:getConst('YES')} */ public static Object getConst(String field) { try { return Global.class.getField(field).get(null); } catch (Exception e) { logger.error("獲得常量失足", e); } return null; } /** * 獲得工程途徑 * @return */ public static String getProjectPath(){ // 假如設置裝備擺設了工程途徑,則直接前往,不然主動獲得。 String projectPath = Global.getConfig("projectPath"); if (StringUtils.isNotBlank(projectPath)){ return projectPath; } try { File file = new DefaultResourceLoader().getResource("").getFile(); if (file != null){ while(true){ File f = new File(file.getPath() + File.separator + "src" + File.separator + "main"); if (f == null || f.exists()){ break; } if (file.getParentFile() != null){ file = file.getParentFile(); }else{ break; } } projectPath = file.toString(); } } catch (IOException e) { logger.error("加載設置裝備擺設文件掉敗", e); } return projectPath; } }
CookieUtil.java 從稱號就曉得是針對獲得和存儲cookie的一個對象類
package com.store.base.secondmodel.base.util; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Cookie對象類 * @author yiyong_wu * */ public class CookieUtils { private static final Logger logger = LoggerFactory.getLogger(CookieUtils.class); /** * 公有結構函數 */ private CookieUtils() { } /** * 設置 Cookie(生成時光為1年) * @param name 稱號 * @param value 值 */ public static void setCookie(HttpServletResponse response, String name, String value) { setCookie(response, name, value, 60*60*24*365); } /** * 設置 Cookie * @param name 稱號 * @param value 值 * @param maxAge 生計時光(單元秒) * @param uri 途徑 */ public static void setCookie(HttpServletResponse response, String name, String value, String path) { setCookie(response, name, value, path, 60*60*24*365); } /** * 設置 Cookie * @param name 稱號 * @param value 值 * @param maxAge 生計時光(單元秒) * @param uri 途徑 */ public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) { setCookie(response, name, value, "/", maxAge); } /** * 設置 Cookie * @param name 稱號 * @param value 值 * @param maxAge 生計時光(單元秒) * @param uri 途徑 */ public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) { Cookie cookie = new Cookie(name, null); cookie.setPath(path); cookie.setMaxAge(maxAge); try { cookie.setValue(URLEncoder.encode(value, "utf-8")); } catch (UnsupportedEncodingException e) { logger.error("不支撐的編碼", e); } response.addCookie(cookie); } /** * 取得指定Cookie的值 * @param name 稱號 * @return 值 */ public static String getCookie(HttpServletRequest request, String name) { return getCookie(request, null, name, false); } /** * 取得指定Cookie的值,並刪除。 * @param name 稱號 * @return 值 */ public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name) { return getCookie(request, response, name, true); } /** * 取得指定Cookie的值 * @param request 要求對象 * @param response 呼應對象 * @param name 名字 * @param isRemove 能否移除 * @return 值 */ public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemove) { String value = null; Cookie[] cookies = request.getCookies(); if(cookies == null) { return value; } for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { try { value = URLDecoder.decode(cookie.getValue(), "utf-8"); } catch (UnsupportedEncodingException e) { logger.error("不支撐的編碼", e); } if (isRemove) { cookie.setMaxAge(0); response.addCookie(cookie); } } } return value; } }
SpringContextHolder.java 重要是用來在java代碼中獲得以後的ApplicationContext,須要在spring設置裝備擺設文件中設置裝備擺設這個bean而且懶加載設置成false;
package com.store.base.secondmodel.base.util; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; @Service @Lazy(false) public class SpringContextHolder implements ApplicationContextAware, DisposableBean { private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class); private static ApplicationContext applicationContext = null; /** * 獲得存儲在靜態變量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { assertContextInjected(); return applicationContext; } /** * 從靜態變量applicationContext中獲得Bean, 主動轉型為所賦值對象的類型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { assertContextInjected(); return (T) applicationContext.getBean(name); } /** * 從靜態變量applicationContext中獲得Bean, 主動轉型為所賦值對象的類型. */ public static <T> T getBean(Class<T> requiredType) { assertContextInjected(); return applicationContext.getBean(requiredType); } @Override public void destroy() throws Exception { SpringContextHolder.clearHolder(); } /** * 完成ApplicationContextAware接口, 注入Context到靜態變量中. */ @Override public void setApplicationContext(ApplicationContext applicationContext) { logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext); SpringContextHolder.applicationContext = applicationContext; if (SpringContextHolder.applicationContext != null) { logger.info("SpringContextHolder中的ApplicationContext被籠罩, 原有ApplicationContext為:" + SpringContextHolder.applicationContext); } } /** * 消除SpringContextHolder中的ApplicationContext為Null. */ public static void clearHolder() { if (logger.isDebugEnabled()){ logger.debug("消除SpringContextHolder中的ApplicationContext:" + applicationContext); } applicationContext = null; } /** * 檢討ApplicationContext不為空. */ private static void assertContextInjected() { Validate.validState(applicationContext != null, "applicaitonContext屬性未注入, 請在applicationContext.xml中界說SpringContextHolder."); } }
StringUtils.java字符串相干的一個對象類
package com.store.base.secondmodel.base.util; import java.io.UnsupportedEncodingException; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.LocaleResolver; import com.store.base.util.Encodes; /** * 字符串贊助類 * @author yiyong_wu * */ public class StringUtils extends org.apache.commons.lang3.StringUtils { private static final char SEPARATOR = '_'; private static final String CHARSET_NAME = "UTF-8"; private static final Logger logger = LoggerFactory.getLogger(StringUtils.class); /** * 轉換為字節數組 * @param str * @return */ public static byte[] getBytes(String str){ if (str != null){ try { return str.getBytes(CHARSET_NAME); } catch (UnsupportedEncodingException e) { logger.error("", e); return new byte[0]; } }else{ return new byte[0]; } } /** * 轉換為字節數組 * @param str * @return */ public static String toString(byte[] bytes){ try { return new String(bytes, CHARSET_NAME); } catch (UnsupportedEncodingException e) { logger.error("", e); return EMPTY; } } /** * 能否包括字符串 * @param str 驗證字符串 * @param strs 字符串組 * @return 包括前往true */ public static boolean inString(String str, String... strs){ if (str != null){ for (String s : strs){ if (str.equals(trim(s))){ return true; } } } return false; } /** * 調換失落HTML標簽辦法 */ public static String replaceHtml(String html) { if (isBlank(html)){ return ""; } String regEx = "<.+?>"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(html); return m.replaceAll(""); } /** * 調換為手機辨認的HTML,去失落款式及屬性,保存回車。 * @param html * @return */ public static String replaceMobileHtml(String html){ if (html == null){ return ""; } return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>"); } /** * 調換為手機辨認的HTML,去失落款式及屬性,保存回車。 * @param txt * @return */ public static String toHtml(String txt){ if (txt == null){ return ""; } return replace(replace(Encodes.escapeHtml(txt), "\n", "<br/>"), "\t", " "); } /** * 縮略字符串(不辨別中英文字符) * @param str 目的字符串 * @param length 截取長度 * @return */ public static String abbr(String str, int length) { if (str == null) { return ""; } try { StringBuilder sb = new StringBuilder(); int currentLength = 0; for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) { currentLength += String.valueOf(c).getBytes("GBK").length; if (currentLength <= length - 3) { sb.append(c); } else { sb.append("..."); break; } } return sb.toString(); } catch (UnsupportedEncodingException e) { logger.error("", e); } return ""; } /** * 轉換為Double類型 */ public static Double toDouble(Object val){ if (val == null){ return 0D; } try { return Double.valueOf(trim(val.toString())); } catch (Exception e) { logger.error("", e); return 0D; } } /** * 轉換為Float類型 */ public static Float toFloat(Object val){ return toDouble(val).floatValue(); } /** * 轉換為Long類型 */ public static Long toLong(Object val){ return toDouble(val).longValue(); } /** * 轉換為Integer類型 */ public static Integer toInteger(Object val){ return toLong(val).intValue(); } /** * 取得i18n字符串 */ public static String getMessage(String code, Object[] args) { LocaleResolver localLocaleResolver = SpringContextHolder.getBean(LocaleResolver.class); HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); Locale localLocale = localLocaleResolver.resolveLocale(request); return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale); } /** * 取得用戶長途地址 */ public static String getRemoteAddr(HttpServletRequest request){ String remoteAddr = request.getHeader("X-Real-IP"); if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("X-Forwarded-For"); } if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("Proxy-Client-IP"); } if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("WL-Proxy-Client-IP"); } return remoteAddr != null ? remoteAddr : request.getRemoteAddr(); } /** * 駝峰定名法對象 * @return * toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCamelCase(String s) { String s1 =s; if (s1 == null) { return null; } s1 = s.toLowerCase(); StringBuilder sb = new StringBuilder(s1.length()); boolean upperCase = false; for (int i = 0; i < s1.length(); i++) { char c = s1.charAt(i); if (c == SEPARATOR) { upperCase = true; } else if (upperCase) { sb.append(Character.toUpperCase(c)); upperCase = false; } else { sb.append(c); } } return sb.toString(); } /** * 駝峰定名法對象 * @return * toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCapitalizeCamelCase(String s) { String s1 = s; if (s1 == null) { return null; } s1 = toCamelCase(s1); return s1.substring(0, 1).toUpperCase() + s1.substring(1); } /** * 駝峰定名法對象 * @return * toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toUnderScoreCase(String s) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean nextUpperCase = true; if (i < (s.length() - 1)) { nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); } if ((i > 0) && Character.isUpperCase(c)) { if (!upperCase || !nextUpperCase) { sb.append(SEPARATOR); } upperCase = true; } else { upperCase = false; } sb.append(Character.toLowerCase(c)); } return sb.toString(); } /** * 轉換為JS獲得對象值,生成三目運算前往成果 * @param objectString 對象串 * 例如:row.user.id * 前往:!row?'':!row.user?'':!row.user.id?'':row.user.id */ public static String jsGetVal(String objectString){ StringBuilder result = new StringBuilder(); StringBuilder val = new StringBuilder(); String[] vals = split(objectString, "."); for (int i=0; i<vals.length; i++){ val.append("." + vals[i]); result.append("!"+(val.substring(1))+"?'':"); } result.append(val.substring(1)); return result.toString(); } }
有了下面這些基本的器械,只須要在寫一個掌握層接口,便可以看到每次前往一個page對象,然後外面封裝好了查詢對象的列表,而且是按分頁得出列表。
package com.store.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.store.base.secondmodel.base.Page; import com.store.base.secondmodel.pratice.model.Product; import com.store.base.secondmodel.pratice.service.ProductService; /** *TODO *2016年10月11日 *yiyong_wu */ @RestController @RequestMapping("/product") public class ProductController { @Autowired private ProductService productService; @ResponseBody @RequestMapping(value="/getPageProduct") public Page<Product> getPageProduct(HttpServletRequest request,HttpServletResponse response){ Page<Product> page = productService.findPage(new Page<Product>(request,response), new Product()); return page; } }
最初在看一下頁面怎樣應用這個page對象,如許我們就完全地引見了這個一個分頁功效,代碼許多,但很完全。
<%@ page contentType="text/html;charset=UTF-8"%> <%@ include file="/WEB-INF/views/include/taglib.jsp"%> <html> <head> <title></title> <meta name="decorator" content="default" /> function page(n, s) { if (n) $("#pageNo").val(n); if (s) $("#pageSize").val(s); $("#searchForm").attr("action", "${ctx}/app/bank/list"); $("#searchForm").submit(); return false; } </script> </head> <body> <form:form id="searchForm" modelAttribute="XXXX" action="${ctx}/XXX" method="post" class="breadcrumb form-search "> <input id="pageNo" name="pageNo" type="hidden" value="${page.pageNo}" /> <input id="pageSize" name="pageSize" type="hidden" value="${page.pageSize}" /> <ul class="ul-form"> <li> <label>能否上架:</label> <form:select id="status" path="status" class="input-medium"> <form:option value="" label=""/> <form:options items="${fns:getDictList('yes_no_app')}" itemLabel="label" itemValue="value" htmlEscape="false"/> </form:select> </li> <li class="btns"><input id="btnSubmit" class="btn btn-primary" type="submit" value="查詢"/> <li class="clearfix"></li> </ul> </form:form> <sys:message content="${message}" /> <sys:message content="${message}" /> <table id="contentTable" class="table table-striped table-bordered table-condensed"> <thead> <tr> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> <th>XXXX</th> </tr> </thead> <tbody> <c:forEach items="${page.list}" var="XXXX"> <tr> <td>${XXXX.name}</td> <td><a href="${ctx}/app/bank/form?id=${XXXX.id}">${XXXX.}</a></td> <td>${XXXX.}</td> <td>${XXXX.}</td> <td>${XXXX.}</td> <td>${fns:getDictLabel(XXXX.isHot, 'yes_no_app', '無')}</td> <td>${XXXX.}</td> <td><c:if test="${XXXX.status==1 }">上架</c:if> <c:if test="${XXXX.status==2 }">下架</c:if> </td> </tr> </c:forEach> </tbody> </table> <div class="pagination">${page} <li >共${page.count}條</li></div> </body> </html>
到這裡就根本上把全部分頁功效描寫得比擬清晰了,願望可以贊助到你們疾速處理分頁這個成績,固然要在前端顯示分頁英俊的話要針對li做一些css款式啥的,最初祝願你可以疾速控制這個分頁功效!
以上所述是小編給年夜家引見的Mybatis經常使用分頁插件完成疾速分頁處置技能,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!