分享一个spring+hibernate的通用分页类

    时间过得真快,已经半年没有更新自己的博客了。    好了,言归正传。大家都知道网上广为流传的一个分页类是:PaginationSupport.java其源代码如下:
    

public class PaginationSupport{

 public final static int PAGESIZE = 30;

 private int pageSize = PAGESIZE;

 private List items;

 private int totalCount;

 private int[] indexes = new int[0];

 private int startIndex = 0;

 public PaginationSupport(List items, int totalCount) {
  setPageSize(PAGESIZE);
  setTotalCount(totalCount);
  setItems(items);
  setStartIndex(0);
 }

 public PaginationSupport(List items, int totalCount, int startIndex) {
  setPageSize(PAGESIZE);
  setTotalCount(totalCount);
  setItems(items);
  setStartIndex(startIndex);
 }

 public PaginationSupport(List items, int totalCount, int pageSize,
   int startIndex) {
  setPageSize(pageSize);
  setTotalCount(totalCount);
  setItems(items);
  setStartIndex(startIndex);
 }

 public List getItems() {
  return items;
 }

 public void setItems(List items) {
  this.items = items;
 }

 public int getPageSize() {
  return pageSize;
 }

 public void setPageSize(int pageSize) {
  this.pageSize = pageSize;
 }

 public int getTotalCount() {
  return totalCount;
 }

 public void setTotalCount(int totalCount) {
  if (totalCount > 0) {
   this.totalCount = totalCount;
   int count = totalCount / pageSize;
   if (totalCount % pageSize > 0)
    count++;
   indexes = new int[count];
   for (int i = 0; i < count; i++) {
    indexes[i] = pageSize * i;
   }
  } else {
   this.totalCount = 0;
  }
 }

 public int[] getIndexes() {
  return indexes;
 }

 public void setIndexes(int[] indexes) {
  this.indexes = indexes;
 }

 public int getStartIndex() {
  return startIndex;
 }

 public void setStartIndex(int startIndex) {
  if (totalCount <= 0)
   this.startIndex = 0;
  else if (startIndex >= totalCount)
   this.startIndex = indexes[indexes.length - 1];
  else if (startIndex < 0)
   this.startIndex = 0;
  else {
   this.startIndex = indexes[startIndex / pageSize];
  }
 }

 public int getNextIndex() {
  int nextIndex = getStartIndex() + pageSize;
  if (nextIndex >= totalCount)
   return getStartIndex();
  else
   return nextIndex;
 }

 public int getPreviousIndex() {
  int previousIndex = getStartIndex() - pageSize;
  if (previousIndex < 0)
   return 0;
  else
   return previousIndex;
 }

 public int getPageCount() {
  int count = totalCount / pageSize;
  if (totalCount % pageSize > 0)
   count++;
  return count;
 }

 public int getCurentPageNum() {
  return getStartIndex() / pageSize + 1;
 }

}
在这个分页类中设定了每页要显示的记录数以及开始索引,如果用普通的jsp来取这个分页类的数据还可以,但是使用spring+hibernate这种架构就显得比较麻烦(原因是spring MVC返回的是一个 PaginationSupport的对象,使用jstl作为前端显示的话,会在jsp页面中掺杂大量的计算,像下一页索引,共多少条记录,当前第几页,共多少页等等会使jsp很难维护)下面是对这个类的改进:

public class  PaginationSupport {
 public final static int PAGESIZE = 30;

 private int pageSize = PAGESIZE;
 
 private int totalCount;

 private int currentPage;

 private int startIndex;
 
 private int[] indexes = new int[0];
 
 private int nextIndex;

 private int previousIndex;

 private int pageCount;

 private List items;
 
 private int lastIndex;
 
 public  PaginationSupport(int pageSize,
   int startIndex) {
  setPageSize(pageSize);
  setStartIndex(startIndex);
  
 }

 public  PaginationSupport(List items, int totalCount) {
  setPageSize(PAGESIZE);
  setTotalCount(totalCount);
  setItems(items);
  setStartIndex(0);
 
 }

 public  PaginationSupport(List items, int totalCount, int startIndex) {
  setPageSize(PAGESIZE);
  setTotalCount(totalCount);
  setItems(items);
  setStartIndex(startIndex);
  
 }

 public  PaginationSupport(List items, int totalCount, int pageSize,
   int startIndex) {
  setPageSize(pageSize);
  setTotalCount(totalCount);
  setItems(items);
  setStartIndex(startIndex);
  
 }

 
 public void setTotalCount(int totalCount) {
  if (totalCount > 0) {
   this.totalCount = totalCount;
   int count = totalCount / pageSize;
   if (totalCount % pageSize > 0)
    count++;
   indexes = new int[count];
   for (int i = 0; i < count; i++) {
    indexes[i] = pageSize * i;
   }
    } else {
   this.totalCount = 0;
  }
 }
 public int getTotalCount() {
  return totalCount;
 }
 public void setIndexes(int[] indexes) {
  this.indexes = indexes;
 }
 public int[] getIndexes() {
  return indexes;
 }

 
 public void setStartIndex(int startIndex) {
  if (totalCount <= 0)
   this.startIndex = 0;
  else if (startIndex >= totalCount)
   this.startIndex = indexes[indexes.length - 1];
  else if (startIndex < 0)
   this.startIndex = 0;
  else {
   this.startIndex = indexes[startIndex / pageSize];
  }
   }
 public int getStartIndex() {
  return startIndex;
 }

 
 public void setNextIndex(int nextIndex) {
  this.nextIndex = nextIndex;
 }
 public int getNextIndex() {
  int nextIndex = getStartIndex() + pageSize;
  if (nextIndex >= totalCount)
   return getStartIndex();
  else
   return nextIndex;
 }
 public void setPreviousIndex(int previousIndex) {
  this.previousIndex = previousIndex;
 }
 
 public int getPreviousIndex() {
  int previousIndex = getStartIndex() - pageSize;
  if (previousIndex < 0)
   return 0;
  else
   return previousIndex;
 }
 public void setPageCount(int pageCount) {
  this.pageCount = pageCount;
 }
 public int getPageCount() {
  int count = totalCount / pageSize;
  if (totalCount % pageSize > 0)
   count++;
  return count;
 }
 

 public int getCurrentPage() {
  return getStartIndex() / pageSize + 1;
 }

 public void setCurrentPage(int currentPage) {
  this.currentPage = currentPage;
 }

 public void setLastIndex(int lastIndex) {
  this.lastIndex =lastIndex ;
 }
 public int getLastIndex() {
  return indexes[indexes.length-1];
 }

 
 public int getPageSize() {
  return pageSize;
 }

 public void setPageSize(int pageSize) {
  this.pageSize = pageSize;
 }

 

 public List getItems() {
  return items;
 }

 public void setItems(List items) {
  this.items = items;
 }


}
以上是分页的封装类,下面是支持分页查询的方法:
1)
public PaginationSupport findPageByCriteria(
   final DetachedCriteria detachedCriteria, final int pageSize,
   final int startIndex) {
  return (PaginationSupport) getHibernateTemplate().execute(
    new HibernateCallback() {
     public Object doInHibernate(Session session)
       throws HibernateException {
      Criteria criteria = detachedCriteria
        .getExecutableCriteria(session);
      int totalCount = ((Integer) criteria.setProjection(
        Projections.rowCount()).uniqueResult())
        .intValue();
      criteria.setProjection(null);
      List items = criteria.setFirstResult(startIndex)
        .setMaxResults(pageSize).list();
      PaginationSupport ps = new PaginationSupport(items,
        totalCount, pageSize, startIndex);
      return ps;
     }
    }, true);
 }
2)
public  PaginationSupport findPageByQuery( final  String hsql,  final int pageSize,final int startIndex){
     return (PaginationSupport)getHibernateTemplate().execute(
     new  HibernateCallback() {
       public  Object doInHibernate(Session session)  throws  HibernateException, SQLException {
             Query query  =  session.createQuery(hsql);
             int totalCount=query.list().size();
             query.setFirstResult(startIndex);
             query.setMaxResults(pageSize);
             List items  = query.list();
          PaginationSupport ps = new PaginationSupport(items,
       totalCount, pageSize, startIndex);
          return ps;
            
             }
       },true);
  }
你也许会问分页查询为什么会提供两个方法,这两个方法有区别吗?其实这两个方法并无本质区别,DetachedCriteria 也是构造查询语句的与Query功能一致,但是它提供了更加面向对象的方法来写hsql语句。一般人们都倾向第一种方法,但是这种方法并不通用,它有一种查询并不支持,那就是当你要查询的对象并不是一个单一对象的话(例如 你在数据库中有两个表,一个是user,另一个是userinfo,这两个表所对应的对象在hiberante中被指定为共享主键的话,在执行查询的时候就会报类型转换异常,原因是查询出来的对象并不是user而是一个包含user 和userinfo的Object,你若强制把它转换成user类型,肯定会出错),这时你不得不采用第二个方法。当然这只是我个人见解,也许还有地方说的不是很准确,希望大家多多批评指正。
最后是这个分页类的前台显示源代码:
<%@ page language="java" contentType="text/html; charset=gbk"
    pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <link type="text/css" rel="stylesheet" href="../css/panel.css">
    <title>显示所有用户</title>
  </head>
 
  <body>
    <div style="margin:20px auto 30px; width:70%;"><a href="index.jsp" class="btn2">返回首页</a></div>
    <div style="margin:10px auto 0; width:70%;">
    <table width="100%" border="0" cellpadding="0" cellspacing="0">
    <caption>
      显示所有用户
    </caption>
    <tr>
      <td>用户ID</td>
      <td>用户名</td>
   <td>用户昵称</td>
      <td>电子邮件</td>
      <td>注册时间</td>
      <td>详细信息</td>
      <td>用户充值记录</td>
      <td>用户定制服务信息</td>
    </tr>
<c:forEach var="user" items="${userPage.items}">
 <tr>
   <td>${user.intId}</td>
      <td>${user.username}</td>
      <td>${user.name}</td>
      <td>${user.email}</td>
      <td><fmt:formatDate value='${user.creationTime}' pattern='yyyy-MM-dd HH:mm' /></td>
   <td><a href="user_getdetailUser.ado?userId=${user.intId}" class="btn">详细信息</a></td>
   <td><a href="orderService_getUserAccountAdds.ado?userId=${user.intId}" class="btn">用户充值记录</a></td>
   <td><a href="orderService_getUserChargeItems.ado?userId=${user.intId}" class="btn">用户定制服务信息</a></td>
 </tr>
</c:forEach>
  </table>
   <c:if test="${!empty userPage}">
     共${userPage.totalCount}记录
     <c:choose>
      <c:when test="${userPage.startIndex ne '0'}">
       <a href="user_getPage.ado?startIndex=0">首页</a>
      </c:when>
      <c:otherwise>
       首页
      </c:otherwise>
     </c:choose>
     <c:choose>
      <c:when test="${userPage.previousIndex lt userPage.startIndex}">
       <a href="user_getPage.ado?startIndex=${userPage.previousIndex }">上一页</a>
      </c:when>
      <c:otherwise>
       上一页
      </c:otherwise>
     </c:choose>
     <c:choose>
      <c:when test="${userPage.nextIndex>userPage.startIndex}">
       <a href="user_getPage.ado?startIndex=${userPage.nextIndex}">下一页</a>
      </c:when>
      <c:otherwise>
       下一页
      </c:otherwise>
     </c:choose>
     <c:choose>
      <c:when test="${userPage.lastIndex eq userPage.startIndex}">
       最后一页
      </c:when>
      <c:otherwise>
       <a href="user_getPage.ado?startIndex=${userPage.lastIndex}">最后一页</a>
      </c:otherwise>
     </c:choose>
     每页显示${userPage.pageSize}条记录
     当前第${userPage.currentPage }/${userPage.pageCount}页
  </c:if>
    </div>
  </body>
</html>


Java分页类定义和使用 文档为Java中进行分页的结构,使用了常见的分页结构,以用来返回给前段指定分页范围的数据。 立即下载

相关推荐

分页Page类

分页查询时,可以用来封装对象, 实现分页查询////////

常见的分页方式

1.概念 物理分页:利用数据库本身提供的分页方式,如mysql的limit,oracle的rownum,好处是效率高,不好的地方就是不同的数据库有不同的搞法。如hibernate采用的是物理分页。 逻辑分页:利用游标分页,好处是数据库兼容,坏处是效率太低。 真分页:确定要显示的页面内容数量,按需查询,效率高,但访问数据库频繁,大型网站都用真分页。 假分页:一次性从数据库查出所有的数据并在页

biaozhun90的博客 2504

安卓app逆向破解脱壳教程

From:Hook 神器家族的 Frida 工具使用详解:https://blog.youkuaiyun.com/FlyPigYe/article/details/90258758 详解 Hook 框架 frida (信抢红包):https://www.freebuf.com/company-information/180480.html APP逆向神器之Frida【Android初级篇】:https://www.jianshu.com/p/2d755beb1c54 frida 官网文档:https://fr..

sinat_28371057的博客 2万+

几种分页方式分析.

一.逻辑分页   1.逻辑分页的第一种方式,利用ResultSet的滚动分页。步骤如下:  a.根据条件sql查询数据库。  b.得到ResultSet的结果集,由于ResultSet带有游标,因此可以使用其next()方法来指向下一条记录。  c.利用next()方法,得到分页所需的结果集。  这种分页方式依靠的是对结果集的算法来分页,因此通常被称为“逻辑分页”。  代码如下: ...

weixin_34417183的博客 660

GO与KEGG富集分析实战:从差异基因到功能注释

本文详细介绍了GO与KEGG富集分析的完整实战流程,从差异基因列表出发,通过基因ID转换、核心分析到结果可视化,系统阐述了如何将基因数据转化为生物学洞察。文章重点讲解了使用R语言clusterProfiler包进行GO和KEGG富集分析的具体步骤、参数设置及常见问题解决方案,并强调了结果解读与生物学故事构建的方法,帮助研究者深入理解差异基因的集体功能倾向。

weixin_29291863的博客 918

在Unity3d使用yolov8的onnx模型

输出OUTPUTS是float32[1,35,8400],表示它会输出一个大小为[1, 35, 8400]的浮点数张量。这个输出张量的维度表示了检测到的目标的数量、每个目标的预测参数以及网格单元的数量。输出张量的第一个维度1表示检测到的目标数量。每个目标由35个值组成,表示目标的类别、置信度、边界框的坐标及10个特定点的位置。要取得8400个数据中置信度最高的数据,然后获取该数据其他channel的数据。运行结果:(蓝色是检测手的边框,红点是自定义的点),其中的四个数字分别表示不同的维度。

shenqingyu0605202324的博客 5603

Java中Page分页类的属性要点

分页

玩转Java 6109

R语言机器学习算法实战系列(十五)随机森林生存预后模型+SHAP值 (Random Survival Forest + SHAP)

本教程运用随机森林生存分析筛选与患者生存状态显著相关特征。该方法借随机森林这一强大机器学习算法,构建多棵决策树并集成结果,以提高生存分析准确性,识别关键生物标志物。接着,利用选定特征构建风险得分,将多个特征转化为单一数值,量化患者风险水平。之后,依据风险得分将患者分为高、低风险亚型,为临床治疗提供个性化指导。最后,通过分析时间依赖的 ROC 曲线评估模型长期预测能力。此曲线计算不同阈值下的真正例率与假正例率,在多个时间点评估,全面展现模型长期稳定性与准确性。。并且增加了SHAP值评估特征重要性

专注生信领域 2623

在Django项目中封装分页类并使用分页类

在 utils 目录下创建 pagination.py 文件( 写项目用【pagination.py】公共组件)。在 app 目录下创建一个新文件夹 utils 文件夹。通过从数据库中提取数据的形式分析如何分页。分页的逻辑和处理规则。

qq_61565654的博客 612

Open3D 计算点云基本特征

在 Open3D 中,可以通过 PCA(主成分分析)来求得点云的特征值和特征向量。然后基于这些特征值,进一步计算各种几何特征,如线性、平面性、球度等。

纵马踏花向自由 1606

【WorkBuddy专栏27】WorkBuddy 和 CodeBuddy 到底什么关系——一篇文章终结所有混淆

WorkBuddy 和 CodeBuddy 到底什么关系——一篇文章终结所有混淆

AI人人懂 2675

spring+hibernate+shiro+Ehcache 项目分享

这篇文章,我将 把一个 spring+hibernate+shiro+Ehcache 完整的集成流程记录下来,源码亦将分享出来。但是好像csdn传资源必须要指定积分的,所以我不得已选择了2分。但这里不要在意细节了。我主要是记录,遇到问题和开发心得。

u011998835的博客 729

【文献笔记】CVPR 2023|Attention-Based Point Cloud Edge Sampling

优点能够有效采出点云数据的边缘点分类任务性能优越不足没有设计出一个更好的上采样方法,导致分割任务的性能略低只考虑了边缘特征,没有利用其他几何特征。

m0_55908255的博客 319

spring and hibernate,spring and tapestry整合篇

目前java开源框架真可以说是琳琅满目,最近一个多星期一直在接触spring、hibernate、tapestry。将最近一个多星期以来的学习汇总一下,以便日后查阅,也方便大家学习。简单的介绍到处都是,对于spring、hibernate、tapestry是干什么用的,我就不多介绍了。大致能够知道spring的IOC/DI概念(AOP方面我也理解不好,暂时)、hibernate的基本概念,如对象持

清澈反省 1682

模型泛化能力提升:领域自适应与迁移学习

模型泛化能力提升:领域自适应与迁移学习​ ,人工智能,计算机视觉,大模型,AI,在机器学习和深度学习的应用中,模型的泛化能力是一个关键问题。泛化能力指的是模型在新的、未见过的数据上表现良好的能力。然而,实际情况中,训练数据和测试数据往往来自不同的领域,存在分布差异,这会导致模型的泛化能力下降。领域自适应与迁移学习正是为了解决这一问题而发展起来的重要技术。

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 3万+

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

实现一个通用分页查询接口

我们使用的持久层框架是:jpa + hibernate 经常使用到里面的动态查询。 最开始使用的时候觉得:窝草!还能这样玩。 写了一年多代码后..... 尼玛,不想写了。 于是乎,我最近想写个通用型的分页查询接口,只需要传递一个实体类就执行查询了, 再也不需要为了做一个查询还写repository,serivec,serviceImpl。想想都开心! 于是乎我决定先做一个demo版: ...

weixin_34088598的博客 1057

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring MVC 4 + Spring Security 4 + Hibernate +JPA实战

最近花了有三个星期把spring实战学了遍,同时也把maven,git,Hibernate给用上了,确实比较锻炼手。登陆,注册(我前端不是很好)是网上找得模版,(提前说下界面做的很挫,是用来练手的,还有很多写的不是很好的代码,我会慢慢完善的,但功能是全的)登陆之后 用来报名考试用的 之后 点了之后,就会扣除你的钱,你也会报名成功。如果不成功就会跳转第一步pom.xml<project

github_31804537的博客 2352

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

maven搭建SpringMvc Hibernate Spring的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd

Mr_PengK的博客 2242

Spring基础分析08-集成JPA/Hibernate进行ORM操作

Spring框架通过其数据访问抽象层,为JPA/Hibernate提供了卓越的支持,使得ORM操作变得更加简单、直观且高效。Hibernate是JPA的一个开源实现,除了遵循JPA规范外,还提供了许多额外的功能,如二级缓存、查询语言HQL等。通过Spring集成JPA/Hibernate进行ORM操作,不仅可以简化数据访问层的实现,还能充分发挥两者的优势,满足复杂的企业级应用需求,欢迎大家一起沟通交流~对于一些复杂的场景,比如需要在一个方法中多次开始和结束事务,编程式事务管理提供了更大的灵活性。

fengxiaotao_cool的专栏 704

springMVC+Hibernate4+Spring整合一(配置文件部分)

本实例采用

Edwards_June的专栏 2502

Hibernate+Spring+Struts2整合开发中的一个分页显示方案

分页显示一直是web开发中一大烦琐的难题,传统的网页设计只在一个JSP或者ASP页面中书写所有关于数据库操作的代码,那样做分页可能简单一点,但当把网站分层开发后,分页就比较困难了,下面是我做Spring+Hibernate+Struts2项目时设计的分页代码,与大家分享交流。     1、DAO层接口的设计,在MemberDao接口中定义了如下两个方法:  public interface M

jzhf2012的专栏 2000

Jersey+Spring+Hibernate整合

前言

xiaochutian的专栏 2004

Spring 整合Hibernate学习笔记

整合的目的是让IOC 容器来管理 Hibernate 的 SessionFactory,让Hibernate 使用Spring 来进行事务管理。 具体步骤: 1.加入所需jar包 2.添加 hibernate 的配置文件: hibernate.cfg.xml,编写了持久化类对应的 .hbm.xml 文件 3.把hibernate加入到spring的配置文件 spring整合文件: ...

sky892012的博客 314

ajax关键知识点之Spring整合Hibernate的DAO层开发解析

本文解析了Spring整合Hibernate实现DAO层开发的关键技术。DAO层作为"数据库翻译官",隔离业务逻辑与数据访问,提升系统可维护性。Spring通过HibernateDaoSupport简化操作,LocalSessionFactoryBean管理SessionFactory配置。文章详细介绍了DAO接口与实现类的设计模式,以及N-1和1-N关联中延迟加载的优化策略,强调通过合理配置lazy属性平衡性能。整个方案采用面向接口编程,使数据持久层具有更好的移植性,适用于轻量级Jav

2301_78506709的博客 698
上一篇: Dtree学习
下一篇: 用prototype实现前台表单的验证(无刷新验证用户名,email,验证码等)
haha_1234
博客等级 码龄19年 1粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值