hibernate.cfg.xml:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/demo</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 是否在控制台打印sql语句,true打印,false不打印 -->
<property name="show_sql">true</property>
<!-- 将sql语句格式化再打印 ,格式化了反而不好阅读 <property name="hibernate.format_sql">true</property> -->
<mapping class="com.imooc.page.model.Student"/>
</session-factory>
</hibernate-configuration>
Student.java
package com.imooc.page.model;
import java.io.Serializable;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "t_student")
public class Student implements Serializable {
private static final long serialVersionUID = -7476381137287496245L;
private int id;
private String stuName;
private int age;
private int gender;
private String address;
public Student() {
super();
}
public Student(int id, String stuName, int age, int gender, String address) {
super();
this.id = id;
this.stuName = stuName;
this.age = age;
this.gender = gender;
this.address = address;
}
public Student(Map<String,Object> map){
this.id = (int)map.get("id");
this.stuName = (String)map.get("stu_name");
this.age = (int)map.get("age");
this.gender = (int)map.get("gender");
this.address = (String)map.get("address");
}
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment",strategy = "increment")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "stu_name")
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
@Column(name = "age")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Column(name = "gender")
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
@Column(name = "address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student [id=" + id + ", stuName=" + stuName + ", age=" + age + ", gender=" + gender + ", address="
+ address + "]";
}
}
package com.imooc.page;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static{
try{
configuration.configure();
// serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory();
}catch(Exception e){
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory(){
}
public static Session getSession() throws HibernateException{
Session session = (Session)threadLocal.get();
if(session==null||!session.isOpen()){
if(sessionFactory==null){
rebuildSessionFactory();
}
session = (sessionFactory!=null)?sessionFactory.openSession():null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory(){
try{
configuration.configure();
// serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory();
}catch(Exception e){
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException{
Session session = (Session)threadLocal.get();
threadLocal.set(null);
if(session!=null){
session.close();
}
}
}
HibernateStudentDaoImpl.java
package com.imooc.page.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import com.imooc.page.Constant;
import com.imooc.page.HibernateSessionFactory;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
public class HibernateStudentDaoImpl implements StudentDao {
@SuppressWarnings("unchecked")
@Override
public Pager<Student> findStudent(Student searchModel, int pageNum, int pageSize) {
Pager<Student> result = null;
//存放查询参数
Map<String,Object> paramMap = new HashMap<String,Object>();
String stuName = searchModel.getStuName();
int gender = searchModel.getGender();
StringBuilder hql = new StringBuilder("from Student where 1=1");
StringBuilder countHql = new StringBuilder("select count(id) from Student where 1=1");
if(stuName !=null&&!stuName.equals("")){
hql.append(" and stuName like :stuName");
countHql.append(" and stuName like :stuName");
paramMap.put("stuName", "%"+stuName+"%");
}
if(gender==Constant.GENDER_FEMALE||gender==Constant.GENDER_MALE){
hql.append(" and gender = :gender");
countHql.append(" and gender = :gender");
paramMap.put("gender",gender);
}
// 起始索引
int fromIndex = pageSize * (pageNum - 1);
//存放所有查询出的学生对象
List<Student> studentList = new ArrayList<Student>();
Session session = null;
try {
session = HibernateSessionFactory.getSession();
//获取query对象
Query hqlQuery = session.createQuery(hql.toString());
Query countHqlQuery = session.createQuery(countHql.toString());
//设置查询参数
setQueryParams(hqlQuery,paramMap);
setQueryParams(countHqlQuery,paramMap);
//从第几条记录开始查询
hqlQuery.setFirstResult(fromIndex);
//每页显示多少条记录
hqlQuery.setMaxResults(pageSize);
//获取查询结果
studentList = hqlQuery.list();
//获取总记录条数
List<?> countResult = countHqlQuery.list();
int totalRecord = ((Number)countResult.get(0)).intValue();
// 获取总页数
int totalPage = totalRecord / pageSize;
if (totalRecord % pageSize != 0) {
totalPage = totalPage + 1;
}
//组装pager对象
result = new Pager<>(pageSize, pageNum, totalRecord, totalPage, studentList);
} catch (Exception e) {
throw new RuntimeException("查询所有数据异常!",e);
}finally{
if(session != null){
HibernateSessionFactory.closeSession();
}
}
return result;
}
/**
* 设置查询的参数
* @param query
* @param paramMap
* @return
*/
private Query setQueryParams(Query query,Map<String,Object> paramMap){
if(paramMap!=null&&!paramMap.isEmpty()){
for(Map.Entry<String, Object> param:paramMap.entrySet()){
query.setParameter(param.getKey(), param.getValue());
}
}
return query;
}
}
HibernateStudentServiceImpl.java
package com.imooc.page.service;
import com.imooc.page.dao.HibernateStudentDaoImpl;
import com.imooc.page.dao.StudentDao;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
public class HibernateStudentServiceImpl implements StudentService {
private StudentDao studentDao;
public HibernateStudentServiceImpl(){
//创建service实现类时,初始化dao对象
studentDao = new HibernateStudentDaoImpl();
}
@Override
public Pager<Student> findStudent(Student searchModel, int pageNum, int pageSize) {
Pager<Student> result = studentDao.findStudent(searchModel, pageNum, pageSize);
return result;
}
public StudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
}
HibernateServlet.java
package com.imooc.page.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HibernateServlet extends HttpServlet {
private static final long serialVersionUID = -4873699362194465829L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("hibernateStudent.jsp").forward(request, response);
}
}
HibernateDataServlet.java:
package com.imooc.page.servlet;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.imooc.page.Constant;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
import com.imooc.page.service.HibernateStudentServiceImpl;
import com.imooc.page.service.StudentService;
public class HibernateDataServlet extends HttpServlet {
private static final long serialVersionUID = -4873699362194465829L;
private StudentService studentService = new HibernateStudentServiceImpl();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
//接收request里的参数
String stuName = request.getParameter("stuName");
int gender = Constant.DEFAULT_GENDER;
String genderStr = request.getParameter("gender");
if(genderStr!=null&&!"".equals(genderStr.trim())){
gender = Integer.parseInt(genderStr);
}
String pageNumStr = request.getParameter("pageNum");
int pageNum = Constant.DEFAULT_PAGE_NUM;
if(pageNumStr!=null&&!"".equals(pageNumStr.trim())){
pageNum = Integer.parseInt(pageNumStr);
}
int pageSize = Constant.DEFAULT_PAGE_SIZE;
String pageSizeStr = request.getParameter("pageSize");
if(pageSizeStr!=null&&!"".equals(pageSizeStr.trim())){
pageSize = Integer.parseInt(pageSizeStr);
}
//组装查询条件
Student searchModel = new Student();
searchModel.setStuName(stuName);
searchModel.setGender(gender);
//调用service获取查询结果
Pager<Student> result = studentService.findStudent(searchModel, pageNum, pageSize);
//不使用缓存
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
//设置超时时间为0
response.addDateHeader("Expires", 0);
//设置编码格式为utf-8
response.setContentType("text/html;charset=utf-8");
//获取查询数据的json格式
String responseStr = JSON.toJSONString(result);
Writer writer = response.getWriter();
writer.write(responseStr);
writer.flush();
}
}
hibernateStudent.jsp
<%@ page language="java" import="java.util.*"
contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生信息</title>
</head>
<%
//获取请求上下文
String context = request.getContextPath();
%>
<link href="../css/pagination.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../js/jquery-1.11.3.js"></script>
<script type="text/javascript" src="../js/jquery.pagination.js"></script>
<script type="text/javascript">
//第一步:页面渲染完之后,请求后台,获取学生数据,加载学生信息
//第二步:完成学生查询功能
//第三步:下拉加载更多数据的功能
var url = "<%=context%>/hibernate/HibernateDataServlet"; //请求获取数据的url
var totalPage = 1;//一共有多少条数据
var pageSize = 30;//每页显示多少条数据
var currentPage = 1;//当前第几页数据,默认为1
var isLoading = false;//标识是否正在加载更多的数据
//页面渲染完之后执行的代码
$(function(){
//绑定事件,监听滚动条下拉的动作
bindScrollEvent();
//请求后台,加载学生信息
queryStudent(1);
});
function queryForm(){
//绑定事件,监听滚动条下拉的动作
bindScrollEvent();
//清空学生的数据
$("#studentDataBody").html("");
//清空学生为空的提示信息
$("#emptyInfo").html("");
//查询学生
queryStudent(1);
}
//请求后台,加载学生信息
function queryStudent(pageNum){
if(pageNum>totalPage){
$("#emptyInfo").html("没有更多的学生数据了……");
$(window).unbind("scroll");
}
if(isLoading){
return;
}else{
isLoading = true;//修改状态为正在加载数据
}
var stuName = $("#stu_name").val();//获取学生姓名
var gender = $("#gender").val();//获取学生姓名
//进行post请求
$.post(url,{"pageSize":pageSize,"pageNum":pageNum,"stuName":stuName,"gender":gender},function(data){
//加载学生信息
totalPage = data.totalPage;//一共有多少条数据
currentPage = data.currentPage;//获取当前第几页数据
var studentList = data.dataList;//学生记录信息
if(totalPage==0){
$("#emptyInfo").html("没有更多的学生数据了……");
}
//加载学生的数据
showStudentData(studentList);
isLoading = false;
},"json")
}
//加载学生的数据
function showStudentData(studentList){
var studentDataHtml = "";
$.each(studentList,function(idx,obj){
studentDataHtml += "<tr>";
studentDataHtml += "<td>"+obj.stuName+"</td>";//获取学生姓名的值
if(obj.gender==1){
studentDataHtml += "<td>男</td>";//获取学生性别的值
}else{
studentDataHtml += "<td>女</td>";//获取学生性别的值
}
studentDataHtml += "<td>"+obj.age+"</td>";//获取学生年龄的值
studentDataHtml += "<td>"+obj.address+"</td>";//获取学生家庭住址的值
studentDataHtml += "</tr>";
});
$("#studentDataBody").append(studentDataHtml);
}
function bindScrollEvent(){
//添加滚动监听事件
$(window).scroll(function(){
var docHeight = $(document).height();//获取整个页面的高度
var winHeight = $(window).height();//获取当前窗体的高度
var winScrollHeight = $(window).scrollTop();//获取滚动条滚动的距离
if(docHeight-30<=winHeight+winScrollHeight){//滚动条到底
//加载更多的学生数据
queryStudent(currentPage+1);
}
});
}
</script>
<body>
<div style="margin-left: 100px; margin-top: 100px;">
<div>
<font color="red">${errorMsg }</font>
</div>
<div>
<form action="#" id="stuForm"
method="post">
姓名 <input type="text" name="stuName" id="stu_name" value="${stuName }"
style="width: 120px;"> 性别 <select name="gender"
id="gender" style="width: 80px">
<option value="0">全部</option>
<option value="1">男</option>
<option value="2">女</option>
</select>
<input type="button" value="查询" onclick="queryForm()">
</form>
</div>
<br> 学生信息列表:<br> <br>
<table border="1px" cellspacing="0px"
style="border-collapse: collapse" id="studentTable">
<thead>
<tr height="30">
<th width="130">姓名</th>
<th width="130">性别</th>
<th width="130">年龄</th>
<th width="130">家庭地址</th>
</tr>
</thead>
<tbody id="studentDataBody">
</tbody>
</table>
<div id="emptyInfo"></div>
<br>
</div>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>pager</display-name>
<servlet>
<servlet-name>SublistServlet</servlet-name>
<servlet-class>com.imooc.page.servlet.SublistServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SublistServlet</servlet-name>
<url-pattern>/sublist/SublistServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>JdbcSqlServlet</servlet-name>
<servlet-class>com.imooc.page.servlet.JdbcSqlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JdbcSqlServlet</servlet-name>
<url-pattern>/jdbcSql/JdbcSqlServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>HibernateServlet</servlet-name>
<servlet-class>com.imooc.page.servlet.HibernateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HibernateServlet</servlet-name>
<url-pattern>/hibernate/HibernateServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>HibernateDataServlet</servlet-name>
<servlet-class>com.imooc.page.servlet.HibernateDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HibernateDataServlet</servlet-name>
<url-pattern>/hibernate/HibernateDataServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
这样,就实现了下拉加载更多数据的功能。