Hibernate是一个优秀的持久层框架,Hibernate充分体现了ORM的设计理念,提供了高效的对象到关系型数据库的持久化服务。它将持久化服务从软件业务层中完全抽取出来,让业务逻辑的处理更加简单,程序之间的各种业务并非紧密耦合,更加有利于高效的开发与维护。
Hibernate的重点在于实体关联关系映射和HQL查询语句,下面给出一个项目代码示例,该示例实现了用户增删查改的功能,使用了JSP,EL,JSTL,Servlet,Filter,Hibernate5(本案例使用的jar包是最新的Hibernate5的jar包,在JDK8,Tomcat9,MySQL5.7的环境下正常运行)等技术,需要用到的jar包有(servlet,jstl,el基本jar包,mysql-connector-java最新jar包,hibernate官网下载的最新required文件夹里面所有的jar包,把所有需要的jar包放在WEB-INF路径下的lib目录下即可),直接上Eclipse项目代码结构图如下:
所有文件的详细代码如下:
package com.kj.test.domain;
import java.io.Serializable;
/**
* 用户实体类
* @author KJ
*
*/
public class User implements Serializable{
private static final long serialVersionUID = 7178219894611819140L;
/** 性别 */
public static final int MAN = 1; //男
public static final int FEMAN = 2; //女
private Long id;
/** 姓名 */
private String name;
/** 性别 */
private Integer sex;
/** 年龄 */
private Integer age;
public User () {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
package com.kj.test.domain;
/**
* 学生实体类
* @author KJ
*
*/
public class Student extends User {
private static final long serialVersionUID = 7178219894611868560L;
/** 学号 */
private String studentId;
/** 班级 */
private NaturalClass naturalClass;
/**学生信息修改*/
private StudentInfoModify studentInfoModify;
public Student () {
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public NaturalClass getNaturalClass() {
return naturalClass;
}
public void setNaturalClass(NaturalClass naturalClass) {
this.naturalClass = naturalClass;
}
public StudentInfoModify getStudentInfoModify() {
return studentInfoModify;
}
public void setStudentInfoModify(StudentInfoModify studentInfoModify) {
this.studentInfoModify = studentInfoModify;
}
}
package com.kj.test.domain;
import java.io.Serializable;
/**
* 学生基本信息修改,信息修改后,需要经过管理员审核,审核通过后方可更新到Student学生实体类中
* @author KJ
*
*/
public class StudentInfoModify implements Serializable {
private static final long serialVersionUID = -2705163477469273274L;
/** 性别 */
public static final int MAN = 1; //男
public static final int FEMAN = 2; //女
private Long id;
/** 对应学生 */
private Student student;
/** 姓名 */
private String name;
/** 性别 */
private Integer sex;
/** 年龄 */
private Integer age;
/** 学号 */
private String studentId;
/** 班级 */
private NaturalClass naturalClass;
public StudentInfoModify() {
}
public StudentInfoModify(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public NaturalClass getNaturalClass() {
return naturalClass;
}
public void setNaturalClass(NaturalClass naturalClass) {
this.naturalClass = naturalClass;
}
}
package com.kj.test.domain;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* 班级实体类
* @author KJ
*
*/
public class NaturalClass implements Serializable{
private static final long serialVersionUID = 7178219894611819142L;
private Long id;
/** 名称 */
private String name;
/** 学生列表 */
private Set<Student> students = new HashSet<Student>();
public NaturalClass () {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Student> getStudents() {
return students;
}
public void setStudents(Set<Student> students) {
this.students = students;
}
}
上面几个类的对应关系配置文件如下:
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.kj.test.domain.User" table="User">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" lazy="false"></property>
<property name="sex" column="sex" lazy="false"></property>
<property name="age" column="age" lazy="false"></property>
</class>
</hibernate-mapping>
Student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- 继承类的配置:Student实体类继续User类 -->
<joined-subclass name="com.kj.test.domain.Student" extends="com.kj.test.domain.User" table="Student">
<key column="id"></key>
<property name="studentId" column="studentId" lazy="false"></property>
<!-- 双向多对一关系:通过hibernate既可以从主控方实体加载被控方的实体,也可以从被控方加载对应的主控方实体 -->
<many-to-one name="naturalClass" column="naturalClassId" lazy="false"></many-to-one>
<!--
一对一关系:
property-ref="student"指定StudentInfoModify类中对应的属性名, lazy="proxy"指定该属性在调用的时候才会被加载,
cascade="delete"当删除Student对象的时候,对应的studentInfoModify对象也会被级联删除
-->
<one-to-one name="studentInfoModify" property-ref="student" lazy="proxy" cascade="delete"></one-to-one>
<!-- 如果是多对多关系,则新建一个类,这个类中引用多对多关系的两个类即可 -->
</joined-subclass>
</hibernate-mapping>
StudentInfoModify.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.kj.test.domain.StudentInfoModify" table="StudentInfoModify">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name" lazy="false"></property>
<property name="sex" column="sex" lazy="false"></property>
<property name="age" column="age" lazy="false"></property>
<property name="studentId" column="studentId" lazy="false"></property>
<!-- 单向多对一关联:只能通过主控方加载被控方数据,其中StudentInfoModify实体类是主控方 -->
<many-to-one name="naturalClass" column="naturalClassId" lazy="false"></many-to-one>
<!-- 一对一关联 -->
<many-to-one name="student" column="stuId" unique="true" not-null="true" lazy="false"></many-to-one>
</class>
</hibernate-mapping>
NaturalClass.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.kj.test.domain.NaturalClass" table="NaturalClass">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" lazy="false"></property>
<!-- 双向多对一关系:通过hibernate既可以从主控方实体加载被控方的实体,也可以从被控方加载对应的主控方实体 -->
<set name="students" inverse="true" lazy="false">
<key column="naturalClassId"></key><!-- 对应Student类中naturalClass属性对应的column值 -->
<one-to-many class="com.kj.test.domain.Student"/>
</set>
</class>
</hibernate-mapping>
上面阐述了实体类中的关联关系,包括继承关系,一对一关系,单向多对一关联,双向多对一关联。
hibernate.cfg.xml主配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置连接数据库的基本信息 -->
<property name="connection.username">root</property><!-- 用户名 -->
<property name="connection.password">root</property><!-- 密码 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property><!-- mysql数据库驱动名 -->
<property name="connection.url">jdbc:mysql://localhost:3306/kj</property><!-- mysql数据库连接URL,其中kj为数据库名 -->
<!-- 配置hibernate的基本信息 -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property><!-- hibernate所使用的数据库方言 -->
<property name="show_sql">false</property><!-- false提高效率,开发可设置为true显示sql语句 -->
<property name="format_sql">true</property><!--是否格式化显示sql语句-->
<property name="hbm2ddl.auto">update</property><!-- 设置为update可动态生成或更新数据库表结构 -->
<mapping resource="com/kj/test/domain/User.hbm.xml" />
<mapping resource="com/kj/test/domain/Student.hbm.xml" />
<mapping resource="com/kj/test/domain/StudentInfoModify.hbm.xml" />
<mapping resource="com/kj/test/domain/NaturalClass.hbm.xml" />
</session-factory>
</hibernate-configuration>
以上所有配置均为正确配置,亲测可用。
Hibernate构建session会话对象工具类
package com.kj.test.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
private static Session session = null;
public static Session getSession() {
if (session == null) {
try {
if (sessionFactory == null) {
Configuration cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory();
}
session = (sessionFactory != null ? sessionFactory.openSession() : null);
} catch (Exception e) {
System.out.println("初始化数据库失败!!!");
e.printStackTrace();
}
}
return session;
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setSessionFactory(SessionFactory sessionFactory) {
HibernateUtil.sessionFactory = sessionFactory;
}
public static void setSession(Session session) {
HibernateUtil.session = session;
}
public static void closeSession(){
try {
if (session != null && session.isOpen()) {
session.close();
}
} catch (Exception e) {
}
}
}
过滤网页传递过来的中文字符Filter类
package com.kj.test.action;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MyFilter implements Filter {
private String encode;
public MyFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (encode != null) {
request.setCharacterEncoding(encode);
response.setContentType("text/html;charset="+encode);
}
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
encode = fConfig.getInitParameter("encode");
}
}
增加用户Servlet
package com.kj.test.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import com.kj.test.domain.User;
import com.kj.test.util.HibernateUtil;
public class AddUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddUserServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取页面传递过来的参数
String name = request.getParameter("name");
String sex = request.getParameter("sex");
String age = request.getParameter("age");
User user = new User(); //实例化用户类
try {
user.setAge(Integer.parseInt(age));
} catch (Exception e) {}
try {
user.setSex(Integer.parseInt(sex));
} catch (Exception e) {}
user.setName(name);
Session session = null;//声明session会话对象
boolean result = false;
try {
session = HibernateUtil.getSession();//获取session
session.beginTransaction();//开启事务
session.save(user);//保存用户
session.getTransaction().commit();//提交事务
result = true;
} catch (Exception e) {
result = false;
session.getTransaction().rollback();//事务回滚
System.out.println("数据添加失败");
e.printStackTrace();
}
String url;
if (result) {
url = "/showUser";
} else {
url = "error.jsp";
}
RequestDispatcher dispathcer = request.getRequestDispatcher(url);
dispathcer.forward(request, response);
}
}
删除用户Servlet
package com.kj.test.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import com.kj.test.domain.User;
import com.kj.test.util.HibernateUtil;
public class DeleteUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DeleteUserServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取页面传递过来的参数
String deleteUserId = request.getParameter("deleteId");
long deleteId = 0;
try {
deleteId = Long.parseLong(deleteUserId);
} catch (Exception e){}
Session session = null;//声明session会话对象
boolean result = false;
try {
session = HibernateUtil.getSession();//获取session
session.beginTransaction();//开启事务
if (deleteId > 0) {
User user = session.get(User.class, deleteId);
if (user != null) {
session.delete(user);//保存用户
}
}
session.getTransaction().commit();//提交事务
result = true;
} catch (Exception e) {
result = false;
session.getTransaction().rollback();//事务回滚
System.out.println("删除对象失败");
e.printStackTrace();
}
String url;
if (result) {
url = "/showUser";
} else {
url = "error.jsp";
}
RequestDispatcher dispathcer = request.getRequestDispatcher(url);
dispathcer.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
显示查询用户列表Servlet
package com.kj.test.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import com.kj.test.domain.User;
import com.kj.test.util.HibernateUtil;
public class ShowUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ShowUserServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String queryName = request.getParameter("queryName");//查询字符串,空字符串代表查询所有
String hql = "from User";//hql查询语句
if (queryName != null) {
hql += " where name like ?";
}
List<User> userList = new ArrayList<User>();//返回对象列表
Session session = null;//声明session对象
try {
session = HibernateUtil.getSession();//获取session对象
Query query = session.createQuery(hql);//创建查询语句,查询不用开启事务
if (queryName != null) {
query.setParameter(0, "%"+queryName+"%");//构建查询参数,防止SQL注入
}
userList = query.list();
} catch (Exception e) {
System.out.println("查询失败");
e.printStackTrace();
}
request.setAttribute("users", userList);
request.setAttribute("queryName", queryName);
String url = "manageUser.jsp";
RequestDispatcher dispathcer = request.getRequestDispatcher(url);
dispathcer.forward(request, response);
}
}
web.xml文件配置Servlet和Filter
<?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>TestHibernate</display-name>
<!-- servlet配置示例 -->
<!-- 增加用户Servlet -->
<servlet>
<servlet-name>AddUserServlet</servlet-name>
<servlet-class>com.kj.test.action.AddUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddUserServlet</servlet-name>
<url-pattern>/addUser</url-pattern>
</servlet-mapping>
<!-- 显示用户Servlet -->
<servlet>
<servlet-name>ShowUserServlet</servlet-name>
<servlet-class>com.kj.test.action.ShowUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowUserServlet</servlet-name>
<url-pattern>/showUser</url-pattern>
</servlet-mapping>
<!-- 删除用户Servlet -->
<servlet>
<servlet-name>DeleteUserServlet</servlet-name>
<servlet-class>com.kj.test.action.DeleteUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DeleteUserServlet</servlet-name>
<url-pattern>/deleteUser</url-pattern>
</servlet-mapping>
<!-- filter配置示例 -->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.kj.test.action.MyFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
添加用户入口页面
<%@ page language="java" 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加用户入口</title>
</head>
<body>
<form action="addUser" method="post">
<div style="margin-top:100px;text-align:center;margin-bottom:10px;font-size:24px;font-weight:bolder">添加用户页面</div>
<table align="center" cellpadding="0" cellspacing="0" >
<tr>
<td style="text-align:right">姓名:</td>
<td style="text-align:left"><input type="text" name="name" value="" required/></td>
</tr>
<tr>
<td style="text-align:right">性别:</td>
<td style="text-align:left"><input type="radio" name="sex" value="1" required/>男 <input type="radio" name="sex" value="2" required/>女</td>
</tr>
<tr>
<td style="text-align:right">年龄:</td>
<td style="text-align:left"><input type="text" name="age" value="" required/></td>
</tr>
</table>
<div style="margin-top:10px;text-align:center;"><input type="submit" value="增加用户"/> <input type="button" value="管理用户" onClick="javascript:location.href='/showUser';"/></div>
</form>
</body>
</html>
管理用户查询列表页面
<%@page import="com.kj.test.domain.User"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
pageContext.setAttribute("MAN",User.MAN);
pageContext.setAttribute("FEMAN",User.FEMAN);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>管理用户页面</title>
</head>
<body>
<form action="/showUser" method="post">
<div style="margin-top:100px;text-align:center;margin-bottom:10px;font-size:24px;font-weight:bolder">管理用户页面</div>
<div style="margin-top:20px;text-align:center;margin-bottom:20px;font-size:16px;font-weight:bolder">
查询用户姓名:<input type="text" name="queryName" value="<c:out value='${param.queryName }'/>"/>
<input type="submit" value="查询" />
</div>
<table align="center" border="1" cellpadding="0" cellspacing="0" >
<c:set var="userList" value="${requestScope.users }" />
<c:if test="${not empty userList }">
<tr>
<th style="text-align:center;width:200px;">主键ID</th>
<th style="text-align:center;width:200px;">姓名</th>
<th style="text-align:center;width:200px;">性别</th>
<th style="text-align:center;width:200px;">年龄</th>
<th style="text-align:center;width:200px;">删除</th>
</tr>
<c:forEach items="${userList }" var="user">
<tr>
<td style="text-align:center;width:200px;"><c:out value="${user.id }"/></td>
<td style="text-align:center;width:200px;"><c:out value="${user.name }"/></td>
<td style="text-align:center;width:200px;"><c:if test="${user.sex == MAN}">男</c:if><c:if test="${user.sex == FEMAN}">女</c:if></td>
<td style="text-align:center;width:200px;"><c:out value="${user.age }"/>岁</td>
<td style="text-align:center;width:200px;"><a href="/deleteUser?deleteId=${user.id }">删除</a></td>
</tr>
</c:forEach>
</c:if>
<c:if test="${empty userList }">
<div style="margin-top:20px;text-align:center;margin-bottom:10px;font-size:18px;font-weight:bolder;color:red">对不起,当前还没有用户记录,请先返回添加页面进行添加。</div>
</c:if>
</table>
<div style="margin-top:20px;text-align:center;"><a href="index.jsp">返回添加页面</a></div>
</form>
</body>
</html>
当系统增删用户出错的时候返回错误提示页面:
<%@ page language="java" 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>错误页面</title>
</head>
<body>
<div style="color:red;text-align:center;margin-top:100px;font-size: 20px;">
操作失败,<a href="/addUser">返回用户添加页面</a>或者<a href="/showUser">返回用户管理页面</a>
</div>
</body>
</html>
至此,项目所有代码已提供完毕,运行jsp页面效果如下:
增加用户页面
增加用户成功后跳转到用户列表页
在列表页可对用户记录进行删除和查询,查询效果图如下: