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(); } }
|