zoukankan      html  css  js  c++  java
  • Hibernate 组合查询+分页

    MVC模型:Hibernate+Struts2

    dao层:

    public List<UserBean> searchList(UserBean uBean,int pageIndex,int pageSize);

    impl层:

    @SuppressWarnings( "unchecked" )
    public List<UserBean> searchList(UserBean uBean,int pageIndex,int pageSize) {
    Session session = HibernateUtils.getSessionFactory().openSession();
    Criteria criteria = session.createCriteria(UserBean.class);
    if (uBean != null) {
    if (StringUtil.isNotEmpty(uBean.getName())) {
    criteria.add(Restrictions.like("name", uBean.getName(),MatchMode.ANYWHERE));
    }
    if (StringUtil.isNotEmpty(uBean.getPwd())) {
    criteria.add(Restrictions.like("pwd", uBean.getPwd(),MatchMode.ANYWHERE));
    }
    if (StringUtil.isNotEmpty(uBean.getType())) {
    criteria.add(Restrictions.like("type", uBean.getType(),MatchMode.ANYWHERE));
    }
    }

    criteria.addOrder(Order.asc("id"));  //根据id排序
    //criteria.addOrder(Order.desc("name"));


    Long totalNum = (Long)criteria.setProjection(Projections.rowCount()).uniqueResult(); //总数量
    int totalPage = (int) ((totalNum + pageSize -1) / pageSize);
    int startIndex = (pageIndex-1)*pageSize;


    criteria.setProjection(null);
    criteria.setFirstResult(startIndex);
    criteria.setMaxResults(pageSize);
    System.out.println("总数="+totalNum+"总页数="+totalPage);

    List<UserBean> list = criteria.list();
    /*Iterator iterator = list.iterator();    //测试 -- 打印返回数据
    while (iterator.hasNext()) {
    UserBean userBean = (UserBean) iterator.next();
    System.out.println("============"+userBean.getName()+","+userBean.getCreateTime());
    }*/
    return list;

    }

    server层:

    public List<UserBean> searchBeans(UserBean uBean,int pageIndex,int pageSize){
    List<UserBean> list = (List<UserBean>) dao.searchList(uBean,pageIndex,pageSize);
    if (list.size() > 0) {
    for (int i = 0; i < list.size(); i++) {
    System.out.println("-------数据信息为:"+list.get(i).getId()+","+list.get(i).getName()+","+list.get(i).getCreateTime());
    }
    System.out.println("=====每页条目数="+pageSize);
    }
    return list;
    }

    调用:

    //方法

    public static String queryByUserBean() throws Exception{
    UserBeanServerDaoImpl sImpl = new UserBeanServerDaoImpl();
    UserBean uBean = new UserBean();
    //uBean.setName("bb");
    //uBean.setPwd("45");
    //uBean.setType("1");
    int pageIndex = 3;
    int pageSize = 10;
    sImpl.searchBeans(uBean,pageIndex,pageSize);
    return null;
    }

    public static void main(String[] args) {

    try {

    queryByUserBean();    //测试

    } catch (Exception e) {
    e.printStackTrace();
    }
    }

  • 相关阅读:
    [译]Java例解Interface
    【笔记】2014-01至2014-02
    【笔记】2013-12
    【笔记】2013-10至2013-11
    【笔记】2013-09
    【笔记】2013-08
    【笔记】2013-07
    生活工作中好用的快捷键和小工具(更新)
    Android Studio更新Gradle问题
    gradle构建spring5源码
  • 原文地址:https://www.cnblogs.com/min77/p/6438022.html
Copyright © 2011-2022 走看看