泛型DAO
package com.oracle.dao;
import java.util.List;
import com.oracle.util.Pagination;
public interface GenericDao<T,PK>{
publicT save(T entity);
publicT findById(PK id); //主键
publicList<T> findAll();
publicvoid update(T entity);
publicvoid delete(T entity);
publicObject queryUniqueObject(String hql,Object[] params);
//分页
publicPagination<T>queryByPageList(String hql,Object[] params,intpageNumber,int pageSize,int maxElements);
}
package com.oracle.dao.impl;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.oracle.dao.GenericDao;
import com.oracle.util.Pagination;
import com.oracle.util.SessionFactoryUtils;
public class GenericDaoImpl<T, PKextends Serializable> implements
GenericDao<T, PK> {
privateClass<T> clazz = null;
//获取当前类的类名
publicGenericDaoImpl() {
clazz = (Class<T>)((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
@Override
publicT save(T entity) {
Session session =SessionFactoryUtils.createSessionFactory() .getCurrentSession();
session.beginTransaction();
session.save(entity);
session.getTransaction().commit();
return entity;
}
@Override
publicT findById(PK id) {
T entity = null;
Session session =SessionFactoryUtils.createSessionFactory() .getCurrentSession();
session.beginTransaction();
entity = (T) session.get(clazz, id);
session.getTransaction().commit();
return entity;
}
@Override
publicList<T> findAll() {
List<T> list = null;
Session session =SessionFactoryUtils.createSessionFactory() .getCurrentSession();
session.beginTransaction();
String hql = "from " +clazz.getName();
Query query = session.createQuery(hql);
list = query.list();
session.getTransaction().commit();
return list;
}
@Override
publicvoid update(T entity) {
Session session =SessionFactoryUtils.createSessionFactory() .getCurrentSession();
session.beginTransaction();
session.update(entity);
session.getTransaction().commit();
}
@Override
publicvoid delete(T entity) {
Session session =SessionFactoryUtils.createSessionFactory() .getCurrentSession();
session.beginTransaction();
session.delete(entity);
session.getTransaction().commit();
}
@Override
publicObject queryUniqueObject(String hql, Object[] params) {
Object obj = null;
Session session =SessionFactoryUtils.createSessionFactory() .getCurrentSession();
session.beginTransaction();
Query query = session.createQuery(hql);
if (params != null) {
for(int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
obj = query.uniqueResult();
session.getTransaction().commit();
return obj;
}
//分页查询
@Override
publicPagination<T> queryByPageList(String hql, Object[] params,
intpageNumber, int pageSize, int maxElements) {
Pagination<T> pagination = newPagination(pageSize, pageNumber, maxElements);
Session session =SessionFactoryUtils.createSessionFactory()
.getCurrentSession();
session.beginTransaction();
Query query = session.createQuery(hql);
if (params != null) {
for(int i = 0; i < params.length; i++) {
query.setParameter(i, params[i]);
}
}
query.setFirstResult((pageNumber-1)*pageSize);
query.setMaxResults(pageSize);
//获取当前页的记录集合
List<T> pageList = query.list();
//给pagination的集合属性赋值
pagination.setPageList(pageList);
session.getTransaction().commit();
return pagination;
}
}
package com.oracle.dao;
import com.oracle.model.GuestBook;
import com.oracle.util.Pagination;
public interface GuestBookDao extendsGenericDao<GuestBook, Integer> {
publicPagination<GuestBook> queryByPageList(int pageNumber,int pageSize);
}
package com.oracle.dao.impl;
import com.oracle.dao.GuestBookDao;
import com.oracle.model.GuestBook;
import com.oracle.util.Pagination;
public class GuestBookDaoImpl extendsGenericDaoImpl<GuestBook, Integer> implements
GuestBookDao {
@Override
publicPagination<GuestBook> queryByPageList(int pageNumber, int pageSize) {
String hql = "from GuestBook orderby createTime desc";
//求总记录数
int maxElements =Integer.parseInt(queryUniqueObject("select count(*) from GuestBook",null).toString());
return queryByPageList(hql, null,pageNumber, pageSize, maxElements);
}
}
package com.oracle.biz;
import java.util.List;
import com.oracle.model.GuestBook;
import com.oracle.util.Pagination;
public interface GuestBookBiz {
publicGuestBook addGuestBook(GuestBook guestBook);
publicList<GuestBook> getAllGuestBooks();
publicPagination<GuestBook> queryByPageList(int pageSize,int pageNumber);
}
package com.oracle.biz.impl;
import java.util.List;
import com.oracle.biz.GuestBookBiz;
import com.oracle.dao.GuestBookDao;
import com.oracle.dao.impl.GuestBookDaoImpl;
import com.oracle.model.GuestBook;
import com.oracle.util.Pagination;
public class GuestBookBizImpl implementsGuestBookBiz {
privateGuestBookDao guestBookDao = new GuestBookDaoImpl();
@Override
publicGuestBook addGuestBook(GuestBook guestBook) {
return guestBookDao.save(guestBook);
}
@Override
publicList<GuestBook> getAllGuestBooks() {
return guestBookDao.findAll();
}
@Override
publicPagination<GuestBook> queryByPageList(int pageSize, int pageNumber) {
return guestBookDao.queryByPageList(pageNumber,pageSize);
}
}
package com.oracle.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oracle.biz.GuestBookBiz;
importcom.oracle.biz.impl.GuestBookBizImpl;
import com.oracle.model.GuestBook;
import com.oracle.util.Pagination;
public class GuestBookAction extendsHttpServlet {
privateGuestBookBiz guestBookBiz = new GuestBookBizImpl();
publicfinal static int PAGESIZE = 6;
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
String page =request.getParameter("p");
int pageNumber = 1;
if(page!=null){
pageNumber= Integer.parseInt(page);
}
Pagination<GuestBook> pagination =guestBookBiz.queryByPageList(PAGESIZE, pageNumber);
request.getSession().setAttribute("pagination",pagination);
request.getRequestDispatcher("pageList.jsp").forward(request,response);
}
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
doGet(request, response);
}
}
package com.oracle.util;
import java.util.List;
public class Pagination<T> {
privateint pageSize = 6; //每页的记录数
privateint pageNumber = 1; //页码
privateint maxElements; //总记录数
privateList<T> pageList; //每页的元素集合
privateint offset; //偏移量
publicPagination() {}
publicPagination(int maxElements) {
this.maxElements = maxElements;
}
publicPagination(int pageSize, int pageNumber, int maxElements) {
this.pageSize = pageSize;
this.maxElements = maxElements;
this.pageNumber = pageNumber;
}
publicint getPageNumber() {
return pageNumber;
}
publicvoid setPageNumber(int pageNumber) {
//计算总页数
int total = (int) Math.ceil(maxElements /pageSize);
//如果当前页码大于总页数
if (pageNumber > total) {
this.pageNumber= total;
} else if (pageNumber <= 1) {
pageNumber= 1;
} else {
this.pageNumber= pageNumber;
}
}
publicvoid setMaxElments(int maxElements) {
this.maxElements = maxElements;
}
publicint getMaxElements() {
return maxElements;
}
publicint getOffset() {
return offset;
}
publicvoid setOffset(int offset) {
if (offset <= 0) {
this.offset= 0;
} else if (offset > maxElements) {
this.offset= maxElements - 1;
} else {
this.offset= offset;
}
}
publicint getPageSize() {
return pageSize;
}
publicList<T> getPageList() {
return pageList;
}
publicvoid setPageList(List<T> pageList) {
this.pageList = pageList;
}
}
package com.oracle.test;
import java.text.SimpleDateFormat;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
importorg.hibernate.criterion.Restrictions;
import com.oracle.model.GuestBook;
import com.oracle.util.SessionFactoryUtils;
public class TestGuestBookCriteria {
publicstatic void main(String[] args) {
// testCriteria();
//testCriteriaByExpression();
testCriteriaPager();
}
privatestatic void testCriteria() {
SessionFactory sessionFactory =SessionFactoryUtils
.createSessionFactory();
Session session =sessionFactory.getCurrentSession();
session.beginTransaction();
// 创建Criteria对象
Criteria criteria =session.createCriteria(GuestBook.class);
// 通过查询返回一个集合
List<GuestBook> guestBooks =criteria.list();
// 遍历集合中的数据
for (GuestBook gb : guestBooks) {
System.out.println(gb.getTitle());
}
session.getTransaction().commit();
}
privatestatic void testCriteriaByExpression() {
SessionFactory sessionFactory =SessionFactoryUtils
.createSessionFactory();
Session session =sessionFactory.getCurrentSession();
session.beginTransaction();
// 创建Criteria对象
Criteria criteria =session.createCriteria(GuestBook.class);
// 创建查询条件对象
Criterion criterion = null;
criterion =Restrictions.eq("ip", "192.168.1.168");
// 添加条件
criteria.add(criterion);
// 再添加筛选条件
criteria.add(Restrictions.like("title","学习H%"));
// 通过查询返回一个集合
List<GuestBook> guestBooks =criteria.list();
// 遍历集合中的数据
for (GuestBook gb : guestBooks) {
System.out.println(gb.getTitle());
}
session.getTransaction().commit();
}
privatestatic void testCriteriaPager() {
SessionFactory sessionFactory =SessionFactoryUtils
.createSessionFactory();
Session session =sessionFactory.getCurrentSession();
session.beginTransaction();
// 创建Criteria对象
Criteria criteria =session.createCriteria(GuestBook.class);
int pageSize = 5;// 每页的记录数
int pageIndex = 3;// 页码
// 设置每页记录的起始索引从0开始
criteria.setFirstResult((pageIndex-1)*pageSize);
// 设置每页显示的记录数
criteria.setMaxResults(pageSize);
//添加排序表达式 :根据时间子程序
criteria.addOrder(Order.desc("createTime"));
// 通过查询返回该页的数据集合
List<GuestBook> guestBooks =criteria.list();
SimpleDateFormat sdf = newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 遍历集合中的数据
for (GuestBook gb : guestBooks) {
System.out.println(gb.getTitle()+"\t"+sdf.format(gb.getCreateTime()));
}
session.getTransaction().commit();
}
}
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<%@ tagliburi="http://jsptags.com/tags/navigation/pager" prefix="pg"%>
<%@ tagliburi="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'pageList.jsp' startingpage</title>
</head>
<body>
<tableborder="1px" width="700px">
<tr>
<th>编号</th>
<th>标题</th>
<th>留言时间</th>
<th>操作</th>
</tr>
<c:forEachitems="${pagination.pageList }" var="guestBook" >
<tr>
<td>${guestBook.id }</td>
<td>${guestBook.title }</td>
<td>${guestBook.createTime}</td>
<td><ahref="viewGuestBook.action?id=${guestBook.id }">查看</a>
<ahref="delGuestBook.action?id=${guestBook.id }">删除</a></td>
</tr>
</c:forEach>
</table>
<!--分页的链接,开始-->
<pg:pagerid="pagination" url="guestBook.do"
items="${pagination.maxElements}"
maxPageItems="${pagination.pageSize}"maxIndexPages="10">
<pg:index>
<pg:prev>
<ahref="${pageUrl}&p=${pageNumber}"><上一页</a>
</pg:prev>
<pg:pages>
<ahref="${pageUrl}&p=${pageNumber}">${pageNumber}</a>
</pg:pages>
<pg:next>
<ahref="${pageUrl}&p=${pageNumber}">下一页></a>
</pg:next>
</pg:index>
</pg:pager>
<!--分页的链接,结束-->
</body>
</html>
导入以下包: