Hibernate(三)
================================HQL=========================
HQL:Hibernate Query Language
from Dept(类名)
范例:Dept类名
1.select dept from Dept as dept
2.from Dept where deptName = 'SALES'
3.from Dept dept where dept.location is not null
dept对象.对象的属性location
4.from Emp order by hireDate,salary desc
步骤:
1.获取Session对象;
2.编写HQL语句;
3.创建Query对象;
4.执行查询,得到查询结果。
a.list()
b.iterate() 先查询id,再执行查询其他(执行n+1次)
JDBC步骤:
1.获取JDBC对象;
2.编写SQL语句;(Structure Query Language)
3.创建PreparedStatement对象;
4.执行查询,得到查询结果。
查询语句中绑定参数:
String hql = "from User where name ='" + name + "'"; -- 不安全,性能地
方法:
a.参数位置绑定
使用 ? 设置占位符 -- from Dept as dept where dept.deptName = ?
b.参数名字绑定(实现动态查询:条件最多3个/条件个数不确定)
使用:name方式设置 -- from Dept as dept where dept.deptName = :name
实现动态查询:
1.封装查询条件
2.动态生成HQL语句
3.使用setProperties赋值
范例:
技巧:
1.转发:/jsp
2.重定向:request.getContextPath()/
1.dept.jsp
startup 启动tomcat
网页是入口,tomcat的main入口
1 <%-- 引入JSP页面PAGE指令 --%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <%-- 引入JSTL标签指令 --%> 5 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 6 <!DOCTYPE html> 7 <html language="zh-CN"> 8 <head> 9 <meta charset="utf-8"> 10 <!-- 设置浏览器渲染的引擎 --> 11 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 12 <!-- 设置支持移动设备 --> 13 <meta name="viewport" content="width=device-width, initial-scale=1"> 14 <title>网页标题</title> 15 <!-- 引用bootstrap样式 --> 16 <link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/bootstrap.min.css"> 17 </head> 18 <body> 19 <div class="container-fluid"> 20 <div class="panel panel-primary"> 21 <div class="panel-heading"><span class="h3">部门信息</span></div> 22 <div class="panel-body"> 23 <form action="<%=request.getContextPath()%>/dept/search?oper=byCondition" method="post">
<label>部门编号</label>
<input name="deptId" type="text"/> 24 <label>部门名称</label> 25 <!-- name与Dept类的属性名一样 --> 26 <input name="deptName" type="text"/> 27 <label>部门位置</label> 28 <input name="location" type="text"/> 29 <input type="submit" value="搜索" data-toggle="search"/> 30 </form> 31 </div> 32 33 <table class="table table-bordered"> 34 <thead> 35 <tr> 36 <td>部门编号</td> 37 <td>部门名称</td> 38 <td>部门位置</td> 39 <td>操作</td> 40 </tr> 41 </thead> 42 <tbody> 43 <c:forEach items="${requestScope.depts }" var="dept"> 44 <tr> 45 <td>${dept.deptId }</td> 46 <td>${dept.deptName }</td> 47 <td>${dept.location }</td> 48 <td><a class="btn btn-primary btn-xs" href="javascript:;">删除</a></td> 49 </tr> 50 51 </c:forEach> 52 </tbody> 53 </table> 54 </div> 55 </div> 56 57 <!-- 引用外部JS文件 --> 58 <script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-2.2.4.js"></script> 59 <script type="text/javascript" src="<%=request.getContextPath() %>/js/bootstrap.min.js"></script> 60 61 <script type="text/javascript"> 62 $(function() { 63 $('[data-toggle="search"]').click(function() { 64 65 }); 66 }); 67 </script> 68 </body> 69 </html>
2.Dept 类
1 package com.Elastic.HibernateDemo3.ivy.entity; 2 3 import java.io.Serializable; 4 import java.util.Set; 5 6 public class Dept implements Serializable { 7 /** 8 * <p> 9 * <h3>作用:</h3> 10 * </p> 11 * @see long 12 * @see serialVersionUID 13 */ 14 private static final long serialVersionUID = 2261199233032137882L; 15 private Integer deptId; 16 private String deptName; 17 private String location;
29 public Integer getDeptId() { 30 return deptId; 31 } 32 public void setDeptId(Integer deptId) { 33 this.deptId = deptId; 34 } 35 public String getDeptName() { 36 return deptName; 37 } 38 public void setDeptName(String deptName) { 39 this.deptName = deptName; 40 } 41 public String getLocation() { 42 return location; 43 } 44 public void setLocation(String location) { 45 this.location = location; 46 } 47 }
3.Dept.hbm.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 6 <hibernate-mapping> 7 <!-- 实体类路径:数据库表名--> 8 <class name="com.Elastic.HibernateDemo3.ivy.entity.Dept" table="dept"> 9 <!-- 主键OID(唯一标识) --> 10 <id name="deptId" column="deptid"><!-- column单独一行,属性更全 --> 11 <!-- 主键生成策略:increment,assigned,native等 --> 12 <generator class="increment"></generator> 13 </id> 14 15 <!-- 属性名(★★setDeptName★★):数据库表字段(如果是关键字,用``标志) --> 16 <property name="deptName" column="deptname"></property> 17 <property name="location" column="location"></property> 18 19 </class> 20 </hibernate-mapping>
6.DeptDao 类
1 package com.Elastic.HibernateDemo3.ivy.dao; 2 3 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 4 public interface DeptDao extends IBaseDao<Dept>{ 5 6 7 }
7.DeptDaoImpl 类
1 package com.Elastic.HibernateDemo3.ivy.dao.impl; 2 3 import com.Elastic.HibernateDemo3.ivy.dao.BaseDao; 4 import com.Elastic.HibernateDemo3.ivy.dao.DeptDao; 5 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 6 7 public class DeptDaoImpl extends BaseDao<Dept> implements DeptDao { 8 9 10 }
4.IBaseDao类
1 package com.Elastic.HibernateDemo3.ivy.dao; 2 3 import java.io.Serializable; 4 import java.util.List; 5 import java.util.Map; 6 public interface IBaseDao<T> { 7 void save(T record); 8 9 //不明确id的类型,就用Serializable 10 void delete(Serializable id); 11 12 void update(T record); 13 14 T findById(Serializable id); 15 16 List<T> find(Map<String, Object> params); 17 18 List<T> find(String hql,Map<String, Object> params); 19 }
5.BaseDao
1 /** 2 * 3 */ 4 package com.Elastic.HibernateDemo3.ivy.dao; 5 6 import java.io.Serializable; 7 import java.lang.reflect.ParameterizedType; 8 import java.util.List; 9 import java.util.Map; 10 11 import org.hibernate.Query; 12 import org.hibernate.Session; 13 14 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 15 //忽略警告 16 @SuppressWarnings({ "rawtypes", "unchecked" }) 17 public class BaseDao<T> implements IBaseDao<T>{ 18 19 private Class entityClass; 20 21 public BaseDao(){ 22 entityClass = this.getEntityClass(); 23 } 24 25 /** 26 * 27 * <p> 28 * <h3>方法功能描述:根据反射得到实体类的类型</h3> 29 * </p> 30 * @return 31 * @procedure 执行过程 32 * @see BaseDao 33 */ 34 private Class getEntityClass(){ 35 try { 36 ParameterizedType paramsType = (ParameterizedType)this.getClass().getGenericSuperclass(); 37 return (Class)paramsType.getActualTypeArguments()[0]; 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } 41 return null; 42 } 43 44 public Session getSession(){ 45 return HibernateUtil.getSession(); 46 } 47 48 @Override 49 public void save(T record){ 50 this.getSession().save(record); 51 } 52 53 @Override 54 public void delete(Serializable id){ 55 this.getSession().delete(this.findById(id)); 56 } 57 58 @Override 59 public void update(T record){ 60 this.getSession().update(record); 61 } 62 63 64 @Override 65 public T findById(Serializable id){ 66 return (T)this.getSession().get(entityClass, id); 67 } 68 69 @Override 70 public List<T> find(Map<String, Object> params){ 71 StringBuffer hql = new StringBuffer("from "); 72 hql.append(entityClass.getName()); 73 hql.append(" where 1 = 1 "); 74 if (null != params) { 75 for (String key : params.keySet()) { 76 hql.append(" and "); 77 hql.append(key); 78 hql.append(" = :"); 79 hql.append(key); 80 } 81 } 82 Query query = this.getSession().createQuery(hql.toString()); 83 if (null != params) { 84 query.setProperties(params); 85 } 86 return query.list(); 87 } 88 89 @Override 90 public List<T> find(String hql, Map<String, Object> params) { 91 Query query = this.getSession().createQuery(hql.toString()); 92 if (null != params) { 93 query.setProperties(params); 94 } 95 return query.list(); 96 } 99 }
8.hibernate.cfg.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 3 <!DOCTYPE hibernate-configuration PUBLIC 4 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 5 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 6 7 <hibernate-configuration> 8 <session-factory> 9 <!-- 1.连接数据库 --> 10 <!-- 连接数据库名 --> 11 <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property> 12 13 <!-- 连接数据库的用户名 --> 14 <property name="connection.username">root</property> 15 16 <!-- 连接数据库的密码 --> 17 <property name="connection.password">root</property> 18 19 <!-- 数据库驱动类 --> 20 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 21 22 <!-- 2.数据库方言(不同的数据库) --> 23 <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> 24 25 <!-- 3.其他属性 --> 26 <!-- 是否显示sql语句 --> 27 <property name="show_sql">true</property> 28 <!-- 是否显示格式化sql语句,如果要显示,★★★一定要先显示show_sql语句★★★ --> 29 <property name="format_sql">true</property> 30 31 <!-- 4.数据库对应的实体类的映射文件路径 --> 32 <mapping resource="com/Elastic/HibernateDemo3/ivy/entity/Dept.hbm.xml"></mapping> 33 </session-factory> 34 </hibernate-configuration>
9.HibernateUtil 类
1 package com.Elastic.HibernateDemo3.ivy.util; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 public final class HibernateUtil { 7 private static Configuration cfg = null; 8 private static SessionFactory sessionFactory = null; 9 10 //本地线程 11 public static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); 12 13 static{ 14 cfg = new Configuration().configure(); 15 sessionFactory = cfg.buildSessionFactory(); 16 } 17 18 public static Session getSession(){ 19 Session session = threadLocal.get(); 20 if (null == session || !session.isOpen()) { 21 session = sessionFactory.openSession(); 22 threadLocal.set(session); 23 } 24 return session; 25 } 26 }
10.OpenSessionInViewFilter 类
1 package com.Elastic.HibernateDemo3.ivy.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 12 import org.hibernate.HibernateException; 13 import org.hibernate.Session; 14 import org.hibernate.Transaction; 15 16 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 17 public class OpenSessionInViewFilter implements Filter{ 18 19 /* (non-Javadoc) 20 * @see javax.servlet.Filter#destroy() 21 */ 22 @Override 23 public void destroy() { 24 // TODO Auto-generated method stub 25 26 } 27 28 /* (non-Javadoc) 29 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) 30 */ 31 @Override 32 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 33 throws IOException, ServletException { 34 35 /* 事务以及session的关闭 */ 36 37 //获取session 38 Session session = HibernateUtil.getSession(); 39 //开启事务 40 Transaction tx = session.beginTransaction(); 41 42 try { 43 chain.doFilter(request, response); 44 //提交事务 45 tx.commit(); 46 } catch (HibernateException e) { 47 tx.rollback(); 48 e.printStackTrace(); 49 } finally { 50 //关闭session 51 session.close(); 52 } 53 54 } 55 56 /* (non-Javadoc) 57 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) 58 */ 59 @Override 60 public void init(FilterConfig arg0) throws ServletException { 61 // TODO Auto-generated method stub 62 63 } 64 65 }
11.EncodingFilter 类
1 package com.Elastic.HibernateDemo3.ivy.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 public class EncodingFilter implements Filter { 12 13 /* (non-Javadoc) 14 * @see javax.servlet.Filter#destroy() 15 */ 16 @Override 17 public void destroy() { 18 // TODO Auto-generated method stub 19 20 } 21 22 /* (non-Javadoc) 23 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) 24 */ 25 @Override 26 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 27 throws IOException, ServletException { 28 request.setCharacterEncoding("utf-8"); 29 response.setCharacterEncoding("utf-8"); 30 chain.doFilter(request, response); 31 } 32 33 /* (non-Javadoc) 34 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) 35 */ 36 @Override 37 public void init(FilterConfig arg0) throws ServletException { 38 // TODO Auto-generated method stub 39 40 } 41 42 }
12.web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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_2_5.xsd" id="WebApp_ID" version="2.5"> 3 <display-name>HibernateDemo3_ivy</display-name> 4 <welcome-file-list> 5 <welcome-file>index.html</welcome-file> 6 <welcome-file>index.htm</welcome-file> 7 <welcome-file>index.jsp</welcome-file> 8 <welcome-file>default.html</welcome-file> 9 <welcome-file>default.htm</welcome-file> 10 <welcome-file>default.jsp</welcome-file> 11 </welcome-file-list> 12 13 <!-- 编码格式放在最前面 --> 14 <filter> 15 <filter-name>encoding</filter-name> 16 <filter-class>com.Elastic.HibernateDemo3.ivy.filter.EncodingFilter</filter-class> 17 </filter> 18 <filter-mapping> 19 <filter-name>encoding</filter-name> 20 <url-pattern>/*</url-pattern> 21 </filter-mapping> 22 23 <!-- 每个操作,事务都能正常操作 --> 24 <filter> 25 <filter-name>OpenSessionInView</filter-name> 26 <filter-class>com.Elastic.HibernateDemo3.ivy.filter.EncodingFilter</filter-class> 27 </filter> 28 <filter-mapping> 29 <filter-name>OpenSessionInView</filter-name> 30 <url-pattern>/*</url-pattern> 31 </filter-mapping> 32 33 <servlet> 34 <description></description> 35 <display-name>DeptServlet</display-name> 36 <servlet-name>DeptServlet</servlet-name> 37 <servlet-class>com.Elastic.HibernateDemo3.ivy.controller.DeptServlet</servlet-class> 38 </servlet> 39 <servlet-mapping> 40 <servlet-name>DeptServlet</servlet-name> 41 <url-pattern>/DeptServlet</url-pattern> 42 <url-pattern>/dept/search</url-pattern> 43 </servlet-mapping> 44 45 </web-app>
13.DeptService 类
1 package com.Elastic.HibernateDemo3.ivy.service; 2 3 import java.util.List; 4 import java.util.Map; 5 6 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 7 8 public interface DeptService{ 9 List<Dept> searchALLDept(); 10 11 List<Dept> searchDeptsByName(String name); 12 13 List<Dept> searchDeptByCondition(Map<String, Object> condition); 14 }
14.DeptServiceImpl 类
1 package com.Elastic.HibernateDemo3.ivy.service.impl; 2 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 import com.Elastic.HibernateDemo3.ivy.dao.DeptDao; 8 import com.Elastic.HibernateDemo3.ivy.dao.impl.DeptDaoImpl; 9 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 10 import com.Elastic.HibernateDemo3.ivy.service.DeptService; 11 12 public class DeptServiceImpl implements DeptService { 13 14 private DeptDao deptDao = new DeptDaoImpl(); 15 16 /* 17 * (non-Javadoc) 18 * 19 * @see com.Elastic.HibernateDemo3.ivy.service.DeptService#searchALLDept() 20 */ 21 @Override 22 public List<Dept> searchALLDept() { 23 return deptDao.find(null); 24 } 25 26 /* 27 * (non-Javadoc) 28 * 29 * @see 30 * com.Elastic.HibernateDemo3.ivy.service.DeptService#searchDeptsByName(java 31 * .lang.String) 32 */ 33 @Override 34 public List<Dept> searchDeptsByName(String name) { 35 Map<String, Object> params = new HashMap<String,Object>(); 36 params.put("deptName", name); 37 38 return deptDao.find(params); 39 } 40 41 @Override 42 public List<Dept> searchDeptByCondition(Map<String, Object> condition) { 43 44 return deptDao.find(condition); 45 } 46 47 }
15.DeptServlet 类
1 package com.Elastic.HibernateDemo3.ivy.controller; 2 3 import java.io.IOException; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 14 import com.Elastic.HibernateDemo3.ivy.service.DeptService; 15 import com.Elastic.HibernateDemo3.ivy.service.impl.DeptServiceImpl; 16 17 18 /** 19 * Servlet implementation class DeptServlet 20 */ 21 public class DeptServlet extends HttpServlet { 22 private static final long serialVersionUID = 1L; 23 24 /** 25 * @see HttpServlet#HttpServlet() 26 */ 27 public DeptServlet() { 28 super(); 29 // TODO Auto-generated constructor stub 30 } 31 32 /** 33 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 34 */ 35 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 36 String oper = request.getParameter("oper"); 37 DeptService deptService = new DeptServiceImpl(); 38 switch (oper) { 39 case "all": 40 List<Dept> depts = deptService.searchALLDept(); 41 request.setAttribute("depts", depts); 42 43 //转发 44 request.getRequestDispatcher("/dept.jsp").forward(request, response); 45 break; 46 case "byName": 47 request.setAttribute("depts", deptService.searchDeptsByName(request.getParameter("name"))); 48 49 //转发 50 request.getRequestDispatcher("/dept.jsp").forward(request, response); 51 break; 52 case "byCondition": 53 //获取页面提交的参数 54 String deptName = request.getParameter("deptName"); 55 String location = request.getParameter("location"); 56 String id = request.getParameter("deptId"); 57 58 //创建保存参数的map集合 59 Map<String, Object> condition = new HashMap<String, Object>(); 60 if (null != deptName && deptName.trim().length() != 0) { 61 //【属性名和页面参数一样要写对!!!】 62 condition.put("deptName", deptName); 63 } 64 if (null != location && location.trim().length() != 0) { 65 //【属性名和页面参数一样要写对!!!】 66 condition.put("location", location); 67 } 68 if (null != id && id.trim().length() != 0) { 69 //【属性名和页面参数一样要写对!!!】 70 condition.put("deptId", Integer.parseInt(id)); 71 } 72 73 request.setAttribute("depts", deptService.searchDeptByCondition(condition)); 74 75 //转发 76 request.getRequestDispatcher("/dept.jsp").forward(request, response); 77 break; 78 79 default: 80 break; 81 } 82 } 83 84 /** 85 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 86 */ 87 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 88 this.doGet(request, response); 89 } 90 91 }