简单记录以下第一次测试 HQL 的步骤和注意事项
建表
建一个最简单的表,这里我建立的是employee,内容如下:
新建项目
项目需要web支持和hibernate支持,新建项目之后,配置好hibernate,连接数据库,自动生成Employee.java和Employee.hbm.xml,展示几个文件的代码:
Employee.java
package com.wyx.HQL;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Objects;
@Entity
public class Employee {
private int id;
private String name;
private String sex;
private int age;
@Id
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "name", nullable = false, length = 45)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "sex", nullable = false, length = 5)
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Basic
@Column(name = "age", nullable = false)
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id &&
age == employee.age &&
Objects.equals(name, employee.name) &&
Objects.equals(sex, employee.sex);
}
@Override
public int hashCode() {
return Objects.hash(id, name, sex, age);
}
}
Employee.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.wyx.HQL.Employee" table="employee" schema="hibernate">
<id name="id">
<column name="id" sql-type="int(10) unsigned"/>
</id>
<property name="name">
<column name="name" sql-type="varchar(45)" length="45"/>
</property>
<property name="sex">
<column name="sex" sql-type="varchar(5)" length="5"/>
</property>
<property name="age">
<column name="age" sql-type="int(10) unsigned"/>
</property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/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://localhost:3306/hibernate?serverTimezone=UTC&characterEncoding=UTF-8</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="connection.username">temp</property>
<property name="connection.password">temp</property>
<mapping class="com.wyx.HQL.Employee"/>
<mapping resource="com/wyx/HQL/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
编写测试的Servlet
QueryEmployeeServlet.java
package com.wyx.HQL;
import com.wyx.hibernate.HibernateUtil;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class QueryEmployeeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("hello!!!!!!!!!!!!!!!!!!!!!!");
request.setCharacterEncoding("UTF-8");
Session session = null;
List emplist = new ArrayList();
try {
session = HibernateUtil.getSession();
String hql = "from Employee emp where emp.sex='n'";
Query query = session.createQuery(hql);
emplist = query.list();
}catch (HibernateException e){
e.printStackTrace();
System.out.println("查询失败");
}finally {
HibernateUtil.closeSession();
}
request.setAttribute("emplist", emplist);
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
里面需要用到HibernateUtil.java文件,如下:
Hibernate.java
package com.wyx.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<>();
private static SessionFactory sessionFactory = null;
static {
try {
Configuration configuration = new Configuration().configure(); // 加载 Hibernate 配置文件
sessionFactory = configuration.buildSessionFactory();
}catch (Exception e){
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}
// 获取 Session
public static Session getSession() throws HibernateException {
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 configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
}catch (Exception e){
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}
// 获取 SessionFactory 对象
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
// 关闭 session
public static void closeSession() throws HibernateException{
Session session = threadLocal.get();
threadLocal.set(null);
if (session != null){
session.close(); // 关闭 Session
}
}
}
修改web.xml页面
需要修改web.xml页面,将初始页改为请求Servlet,不然会重复访问index.jsp,报错
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>QueryEmployeeServlet</servlet-name>
<servlet-class>com.wyx.HQL.QueryEmployeeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>QueryEmployeeServlet</servlet-name>
<url-pattern>/QueryEmployeeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>QueryEmployeeServlet</welcome-file>
</welcome-file-list>
</web-app>
index.jsp
最后效果检验的页面
<%--
Created by IntelliJ IDEA.
User: yuxuan
Date: 2019/3/1
Time: 19:38
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>员工信息列表</title>
<style type="text/css">
table{
border-left: 5px solid #ffffff;
border-collapse: collapse;
}
td{
font: normal 12px/ 17px Arial;
padding: 2px;
}
th{
font: bold 12px/ 17px Arial;
padding: 4px;
border-bottom: 1px solid #333;
}
body{
font-size: 14px;
}
#main{
width: 500px;
border: solid 1px #000000;
}
</style>
</head>
<body>
<div id="main">
<table>
<tr>
<th width="30px">id: </th>
<th width="30px">name: </th>
<th width="30px">sex: </th>
<th width="30px">age: </th>
</tr>
<c:forEach items="${emplist}" var="list">
<tr>
<td align="center">${list.id}</td>
<td>${list.name}</td>
<td>${list.sex}</td>
<td>${list.age}</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
运行结果: