标签:
==================================投影(查询)=============================
投影查询:查询一个持久化类的一个或多个属性值
1.将每条查询结果封装成Object对象
2.将每条查询结果封装成Object数组
3.将每条查询结果通过构造函数封装成对象
范例1:java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.Elastic.HibernateDemo3.ivy.entity.Dept
[L:数组
1 package com.Elastic.HibernateDemo3.ivy.test; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import org.hibernate.Query; 6 import org.hibernate.SQLQuery; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 9 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 10 public class Test { 11 public static void main(String[] args) { 12 Session session = HibernateUtil.getSession(); 13 14 String hql = "select deptName,location from Dept"; 15 16 Query query = session.createQuery(hql); 17 18 //2.将每条查询结果封装成Object数组 19 List<Dept> depts = query.list(); 20 for (Dept dept : depts) { 21 System.out.println(dept.getDeptName()); 22 } 23 } 24 }
范例2: Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: expecting OPEN, found ‘[‘ near line 1, column 16 [select new Dept[deptName,location] from com.Elastic.HibernateDemo3.ivy.entity.Dept]
1 package com.Elastic.HibernateDemo3.ivy.test; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import org.hibernate.Query; 6 import org.hibernate.SQLQuery; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 9 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 10 public class Test { 11 public static void main(String[] args) { 12 Session session = HibernateUtil.getSession(); 13 14 //3.将每条查询结果通过构造函数封装成对象 15 String hql = "select new Dept[deptName,location] from Dept"; 16 17 Query query = session.createQuery(hql); 18 19 List<Dept> depts = query.list(); 20 for (Dept dept : depts) { 21 System.out.println(dept.getDeptName()); 22 } 23 } 24 }
范例3:Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: expecting OPEN, found ‘[‘ near line 1, column 16 [select new Dept[deptName,location] from com.Elastic.HibernateDemo3.ivy.entity.Dept]
1 package com.Elastic.HibernateDemo3.ivy.test; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import org.hibernate.Query; 6 import org.hibernate.SQLQuery; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 9 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 10 public class Test { 11 public static void main(String[] args) { 12 Session session = HibernateUtil.getSession(); 13 14 String hql = "select new Dept[deptName,location] from Dept"; 15 16 Query query = session.createQuery(hql); 17 18 //2.将每条查询结果封装成Object数组 19 <Object> objs = query.list(); 20 for (Object object : objs) { 21 System.out.println(object); 22 } 23 } 24 }
范例4:Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: expecting OPEN, found ‘[‘ near line 1, column 16 [select new Dept[deptName,location] from com.Elastic.HibernateDemo3.ivy.entity.Dept]
1 package com.Elastic.HibernateDemo3.ivy.test; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import org.hibernate.Query; 6 import org.hibernate.SQLQuery; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 9 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 10 public class Test { 11 public static void main(String[] args) { 12 Session session = HibernateUtil.getSession(); 13 //将每条查询结果封装成Object数组与将每条查询结果通过构造函数封装成对象只能选其一??? 14 String hql = "select new Dept[deptName,location] from Dept"; 15 Query query = session.createQuery(hql); 16 List<Object[]> depts = query.list(); 17 for (Object[] objects : depts) { 18 System.out.println(objects[0].toString() + objects[1]); 19 } 20 } 21 }
正确范例:
1 import java.util.HashMap; 2 import java.util.List; 3 import java.util.Map; 4 import org.hibernate.Query; 5 import org.hibernate.SQLQuery; 6 import org.hibernate.Session; 7 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 8 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 9 public class Test { 10 public static void main(String[] args) { 11 Session session = HibernateUtil.getSession(); 12 String hql = "select deptName,location from Dept"; 13 Query query = session.createQuery(hql); 14 List<Object[]> depts = query.list(); 15 for (Object[] objects : depts) { 16 System.out.println(objects[0].toString() + objects[1]); 17 } 18 } 19 }
========================================分页查询===============================================
范例:
1 package com.Elastic.HibernateDemo3.ivy.test; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import org.hibernate.Query; 6 import org.hibernate.SQLQuery; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 9 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 10 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 11 public class Test { 12 public static void main(String[] args) { 13 Session session = HibernateUtil.getSession(); 14 String hql = "from Dept"; 15 Query query = session.createQuery(hql); 16 17 //当前页码 18 int pageIndex = 1; 19 //每页显示的条数 20 int pageSize = 2; 21 22 //设置查询的起始位置 23 query.setFirstResult((pageIndex - 1) * pageSize); 24 //设置每页查询的(最大)条数 25 query.setMaxResults(pageSize); 26 27 List<Dept> depts = query.list(); 28 for (Dept dept : depts) { 29 System.out.println(dept.getDeptName()); 30 } 31 } 32 }
==================================连接查询==============================
内联:只显示互相有值的两表
左外联:左边全部显示,右边null
右外联:右边全部显示,左边null
连接类型 HQL语法
内连接 inner join 或 join
迫切内连接 inner join fetch或 join fetch
左外连接 left outer join或 left join
迫切左外连接 left outer join fetch或 left join fetch
右外连接 right outer join 或right join
注意:配置文件中的fetch属性效果不大,所以一般不在配置文件中使用这个属性。而是在业务有需求时,才在业务中使用
范例:Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.Elastic.HibernateDemo3.ivy.entity.Emp
迫切连接???
1 package com.Elastic.HibernateDemo3.ivy.test; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import org.hibernate.Query; 6 import org.hibernate.SQLQuery; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 9 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 10 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 11 public class Test { 12 public static void main(String[] args) { 13 Session session = HibernateUtil.getSession(); 14 String hql = "from Emp emp inner join emp.dept"; 15 List<Emp> emps = session.createQuery(hql).list(); 16 for (Emp emp : emps) { 17 System.out.println(emp.getEmpName() + emp.getDept().getDeptName()); 18 } 19 } 20 }
正确范例:
1 package com.Elastic.HibernateDemo3.ivy.test; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import org.hibernate.Query; 6 import org.hibernate.SQLQuery; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 9 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 10 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 11 public class Test { 12 public static void main(String[] args) { 13 Session session = HibernateUtil.getSession(); 14 String hql = "from Emp emp inner join emp.dept"; 15 List<Emp> emps = session.createQuery(hql).list(); 16 for (Emp emp : emps) { 17 System.out.println(emp.getEmpName() + emp.getDept().getDeptName()); 18 } 19 } 20 }
===================================子查询================================
子查询语句:应用在HQL查询语句的where子句中
关键字 说明
all 返回的所有记录
any 返回的任意一条记录
some 和“any”意思相同
in 与“=any”意思相同
exists 至少返回一条记录
范例:
a.查询所有员工工资都小于5000的部门
from Dept d where d.emps.size>0 and
5000>all(select e.salary from d.emps e)
b.查询至少有一位员工工资低于5000的部门
from Dept d where 5000>any(select e.salary from d.emps e)
c.查询员工工资正好是5000元的部门
from Dept d where 5000=any(select e.salary from d.emps e)
from Dept d where 5000=some(select e.salary from d.emps e)
d.查询至少有一位员工的部门
from Dept d where exists (from d.emps)
【技巧:size和exists可以表达一件事,优先考虑exists(效率高)】
====================================原生SQL查询================================
HQL 不能"统计"
SQL 提高性能,有相应数据库的优化语法
原生SQL查询:使用底层数据库的SQL特性,来生成一些特殊的查询语句
Hibernate使用★Session的createSQLQuery()方法创建SQLQuery对象★,用来执行原生SQL语句
范例1:
1 package com.Elastic.HibernateDemo3.ivy.test; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import org.hibernate.Query; 6 import org.hibernate.SQLQuery; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 9 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 10 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 11 public class Test { 12 public static void main(String[] args) { 13 Session session = HibernateUtil.getSession(); 14 //直接创建SQL 15 String sql = "select e.*,d.* from emp e inner join dept d on e.deptId = d.deptId"; 16 17 //创建SQLQuery对象,命名查询createSQLQuery() 18 SQLQuery sqlQuery = session.createSQLQuery(sql); 19 sqlQuery.addEntity(Emp.class); 20 21 List<Emp> emps = sqlQuery.list(); 22 for (Emp emp : emps) { 23 System.out.println(emp.getEmpName() + emp.getDept().getDeptName()); 24 } 25 26 //‘:name‘ 相当 SQL语句中的 ‘?‘。其他like等语法HQL一样用 27 Query query = session 28 .createSQLQuery( 29 "select * from Emp where empName like :ename and Job = :job") 30 .addEntity(Emp.class).setString("ename", "%张%") 31 .setString("job", "工程师"); 32 List<Emp> list = query.list(); 33 } 34 }
=================================命名查询=========================
命名查询语句:在映射文件中定义★字符串形式★的查询语句
HQL查询语句的命名查询,存在★***.hbm.xml★
HQL命名查询
SQL命名查询
【技巧:表单 传入两个值name和value。所以 命名时,用Map做】
范例1:
1 <hibernate-mapping> 2 <class name="com.xuetang9.demo.entity.Emp" table="emp"> 3 ...... 4 </class> 5 <query name="findEmpByJob"> 6 <![CDATA[ 7 from Emp e where e.job = :job 8 ]]> 9 </query> 10 </hibernate-mapping>
范例2:
1.Emp.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 <hibernate-mapping> 6 <!-- 实体类路径:数据库表名--> 7 <class name="com.Elastic.HibernateDemo3.ivy.entity.Emp" table="emp"> 8 9 <!-- 主键UID(唯一标识) --> 10 <id name="empNo" column="empNo"><!-- column单独一行,属性更全 --> 11 12 <!-- 主键生成策略:increment,assigned,native等 --> 13 <generator class="increment"></generator> 14 </id> 15 16 <!-- 属性名(★★setDeptName★★):数据库表字段(如果是关键字,用``标志) --> 17 <property name="empName" column="empName"></property> 18 19 <!-- 这个字段进行新增和修改功能,要被Hibernate忽略。因为,与外键一样 --> 20 <property name="deptId" column="deptId" insert="false" update="false"></property> 21 22 23 <!-- 多对一的关系(多个员工属于一个部门) --> 24 <many-to-one name="dept" class="com.Elastic.HibernateDemo3.ivy.entity.Dept" column="deptId" lazy="proxy"></many-to-one> 25 <!-- fetch存在,懒加载没用。fetch不放在配置文件中 --> 26 27 </class> 28 29 <!-- 配置HQL命名查询 --> 30 <query name="findEmpByDeptName"> 31 <!-- 文本 --> 32 <![CDATA[ 33 from Emp e where e.dept.deptName = :deptname and e.empName = :ename 34 ]]> 35 </query> 36 37 <!-- 配置原生的SQL语句 --> 38 <sql-query name="findEmp"> 39 <return alias="e" class="com.Elastic.HibernateDemo3.ivy.entity.Emp"></return> 40 select * from emp e inner join dept d on e.deptId = d.deptId where e.empName = :ename and d.deptName = :deptname 41 </sql-query> 42 </hibernate-mapping>
2.Test类
1 package com.Elastic.HibernateDemo3.ivy.test; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import org.hibernate.Query; 6 import org.hibernate.SQLQuery; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 9 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 10 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 11 public class Test { 12 public static void main(String[] args) { 13 String name = "findEmp"; 14 //String name = "findEmpByDeptName"; 15 Map<String, Object> params = new HashMap<String, Object>(); 16 params.put("deptname", "销售部"); 17 params.put("ename", "李四"); 18 19 Session session = HibernateUtil.getSession(); 20 Query query = session.getNamedQuery(name); 21 query.setProperties(params); 22 List<Emp> emps = query.list(); 23 for (Emp emp : emps) { 24 System.out.println(emp.getEmpName() + emp.getDept().getDeptName()); 25 } 26 } 27 }
=================================综合范例==============================
1.实体类及其hbm.xml文件 -- entity包
a.Dept
1 package com.Elastic.HibernateDemo3.ivy.entity; 2 import java.io.Serializable; 3 import java.util.Set; 4 public class Dept implements Serializable { 5 private static final long serialVersionUID = 2261199233032137882L; 6 private Integer deptId; 7 private String deptName; 8 private String location; 9 10 //多对一:一个部门有多个员工 11 //set:唯一 12 private Set<Emp> emps; 13 14 public Set<Emp> getEmps() { 15 return emps; 16 } 17 public void setEmps(Set<Emp> emps) { 18 this.emps = emps; 19 } 20 21 public Integer getDeptId() { 22 return deptId; 23 } 24 public void setDeptId(Integer deptId) { 25 this.deptId = deptId; 26 } 27 public String getDeptName() { 28 return deptName; 29 } 30 public void setDeptName(String deptName) { 31 this.deptName = deptName; 32 } 33 public String getLocation() { 34 return location; 35 } 36 public void setLocation(String location) { 37 this.location = location; 38 } 39 }
b.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 <!-- 多个员工 --> 20 <!-- <set name="emps" cascade="save-update"> --><!-- 新增部门的同时,新增员工(级联操作) --> 21 <!-- <set name="emps" cascade="all" inverse="true" order-by="empNo desc"> --><!-- 删除部门同时删除员工 --> 22 <set name="emps" cascade="all" inverse="true" order-by="empNo desc" lazy="extra"><!-- 删除部门同时删除员工 23 表dept中deptid --> 24 <key column="deptid"></key> 25 <one-to-many class="com.Elastic.HibernateDemo3.ivy.entity.Emp"></one-to-many> 26 </set> 27 28 </class> 29 </hibernate-mapping>
a1.Emp
1 package com.Elastic.HibernateDemo3.ivy.entity; 2 import java.io.Serializable; 3 public class Emp implements Serializable { 4 /** 5 * <p> 6 * <h3>作用:</h3> 7 * </p> 8 * @see long 9 * @see serialVersionUID 10 */ 11 private static final long serialVersionUID = -6182713107749938132L; 12 private Integer empNo; 13 private String empName; 14 private Integer deptId; 15 16 private Dept dept; 17 18 public Integer getDeptId() { 19 return deptId; 20 } 21 public void setDeptId(Integer deptId) { 22 this.deptId = deptId; 23 } 24 public Dept getDept() { 25 return dept; 26 } 27 public void setDept(Dept dept) { 28 this.dept = dept; 29 } 30 public Integer getEmpNo() { 31 return empNo; 32 } 33 public void setEmpNo(Integer empNo) { 34 this.empNo = empNo; 35 } 36 public String getEmpName() { 37 return empName; 38 } 39 public void setEmpName(String empName) { 40 this.empName = empName; 41 } 42 }
b1.Emp.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 <hibernate-mapping> 6 <!-- 实体类路径:数据库表名--> 7 <class name="com.Elastic.HibernateDemo3.ivy.entity.Emp" table="emp"> 8 9 <!-- 主键UID(唯一标识) --> 10 <id name="empNo" column="empNo"><!-- column单独一行,属性更全 --> 11 12 <!-- 主键生成策略:increment,assigned,native等 --> 13 <generator class="increment"></generator> 14 </id> 15 16 <!-- 属性名(★★setDeptName★★):数据库表字段(如果是关键字,用``标志) --> 17 <property name="empName" column="empName"></property> 18 19 <!-- 这个字段进行新增和修改功能,要被Hibernate忽略。因为,与外键一样 --> 20 <property name="deptId" column="deptId" insert="false" update="false"></property> 21 22 23 <!-- 多对一的关系(多个员工属于一个部门) --> 24 <many-to-one name="dept" class="com.Elastic.HibernateDemo3.ivy.entity.Dept" column="deptId" lazy="proxy"></many-to-one> 25 <!-- fetch存在,懒加载没用。fetch不放在配置文件中 --> 26 27 </class> 28 29 <!-- 配置HQL命名查询 --> 30 <query name="findEmpByDeptName"> 31 <!-- 文本 --> 32 <![CDATA[ 33 from Emp e where e.dept.deptName = :deptname and e.empName = :ename 34 ]]> 35 </query> 36 37 <!-- 配置原生的SQL语句 --> 38 <sql-query name="findEmp"> 39 <return alias="e" class="com.Elastic.HibernateDemo3.ivy.entity.Emp"></return> 40 41 select * from emp e inner join dept d on e.deptId = d.deptId where e.empName = :ename and d.deptName = :deptname 42 </sql-query> 43 </hibernate-mapping>
2.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 <mapping resource="com/Elastic/HibernateDemo3/ivy/entity/Emp.hbm.xml"></mapping> 34 </session-factory> 35 </hibernate-configuration>
3.util包:HibernateUtil
1 package com.Elastic.HibernateDemo3.ivy.util; 2 import org.hibernate.Session; 3 import org.hibernate.SessionFactory; 4 import org.hibernate.cfg.Configuration; 5 public final class HibernateUtil { 6 private static Configuration cfg = null; 7 private static SessionFactory sessionFactory = null; 8 9 //本地线程 10 public static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); 11 12 static{ 13 cfg = new Configuration().configure(); 14 sessionFactory = cfg.buildSessionFactory(); 15 } 16 17 public static Session getSession(){ 18 Session session = threadLocal.get(); 19 if (null == session || !session.isOpen()) { 20 session = sessionFactory.openSession(); 21 threadLocal.set(session); 22 } 23 return session; 24 } 25 }
4.filter包
a.EncodingFilter
1 package com.Elastic.HibernateDemo3.ivy.filter; 2 import java.io.IOException; 3 import javax.servlet.Filter; 4 import javax.servlet.FilterChain; 5 import javax.servlet.FilterConfig; 6 import javax.servlet.ServletException; 7 import javax.servlet.ServletRequest; 8 import javax.servlet.ServletResponse; 9 public class EncodingFilter implements Filter { 10 11 /* (non-Javadoc) 12 * @see javax.servlet.Filter#destroy() 13 */ 14 @Override 15 public void destroy() { 16 // TODO Auto-generated method stub 17 18 } 19 20 /* (non-Javadoc) 21 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) 22 */ 23 @Override 24 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 25 throws IOException, ServletException { 26 request.setCharacterEncoding("utf-8"); 27 response.setCharacterEncoding("utf-8"); 28 chain.doFilter(request, response); 29 } 30 31 /* (non-Javadoc) 32 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) 33 */ 34 @Override 35 public void init(FilterConfig arg0) throws ServletException { 36 // TODO Auto-generated method stub 37 38 } 39 }
b.OpenSessionInViewFilter
1 package com.Elastic.HibernateDemo3.ivy.filter; 2 import java.io.IOException; 3 import javax.servlet.Filter; 4 import javax.servlet.FilterChain; 5 import javax.servlet.FilterConfig; 6 import javax.servlet.ServletException; 7 import javax.servlet.ServletRequest; 8 import javax.servlet.ServletResponse; 9 import org.hibernate.HibernateException; 10 import org.hibernate.Session; 11 import org.hibernate.Transaction; 12 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 13 public class OpenSessionInViewFilter implements Filter{ 14 15 /* (non-Javadoc) 16 * @see javax.servlet.Filter#destroy() 17 */ 18 @Override 19 public void destroy() { 20 // TODO Auto-generated method stub 21 22 } 23 24 /* (non-Javadoc) 25 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) 26 */ 27 @Override 28 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 29 throws IOException, ServletException { 30 31 /* 事务以及session的关闭 */ 32 33 //获取session 34 Session session = HibernateUtil.getSession(); 35 //开启事务 36 Transaction tx = session.beginTransaction(); 37 38 try { 39 chain.doFilter(request, response); 40 //提交事务 41 tx.commit(); 42 } catch (HibernateException e) { 43 tx.rollback(); 44 e.printStackTrace(); 45 } finally { 46 //关闭session 47 session.close(); 48 } 49 } 50 51 /* (non-Javadoc) 52 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) 53 */ 54 @Override 55 public void init(FilterConfig arg0) throws ServletException { 56 // TODO Auto-generated method stub 57 58 } 59 }
5.dao包
a.IBaseDao
1 package com.Elastic.HibernateDemo3.ivy.dao; 2 import java.io.Serializable; 3 import java.util.List; 4 import java.util.Map; 5 import com.Elastic.HibernateDemo3.ivy.common.PageList; 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 20 PageList<T> findByPage(int pageIndex, int pageSize, Map<String, Object> params); 21 22 List<T> findByNamed(String queryName, Map<String, Object> params); 23 }
b.BaseDao
1 package com.Elastic.HibernateDemo3.ivy.dao; 2 import java.io.Serializable; 3 import java.lang.reflect.ParameterizedType; 4 import java.util.List; 5 import java.util.Map; 6 import org.hibernate.Query; 7 import org.hibernate.Session; 8 import com.Elastic.HibernateDemo3.ivy.common.PageList; 9 import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; 10 11 //忽略警告 12 @SuppressWarnings({ "rawtypes", "unchecked" }) 13 public class BaseDao<T> implements IBaseDao<T>{ 14 15 private Class entityClass; 16 17 public BaseDao(){ 18 entityClass = this.getEntityClass(); 19 } 20 21 /** 22 * 23 * <p> 24 * <h3>方法功能描述:根据反射得到实体类的类型</h3> 25 * </p> 26 * @return 27 * @procedure 执行过程 28 * @see BaseDao 29 */ 30 private Class getEntityClass(){ 31 try { 32 ParameterizedType paramsType = (ParameterizedType)this.getClass().getGenericSuperclass(); 33 return (Class)paramsType.getActualTypeArguments()[0]; 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 return null; 38 } 39 40 public Session getSession(){ 41 return HibernateUtil.getSession(); 42 } 43 44 @Override 45 public void save(T record){ 46 this.getSession().save(record); 47 } 48 49 @Override 50 public void delete(Serializable id){ 51 this.getSession().delete(this.findById(id)); 52 } 53 54 @Override 55 public void update(T record){ 56 this.getSession().update(record); 57 } 58 59 60 @Override 61 public T findById(Serializable id){ 62 return (T)this.getSession().get(entityClass, id); 63 } 64 65 @Override 66 public List<T> find(Map<String, Object> params){ 67 StringBuffer hql = new StringBuffer("from "); 68 hql.append(entityClass.getName()); 69 hql.append(" where 1 = 1 "); 70 if (null != params) { 71 for (String key : params.keySet()) { 72 hql.append(" and "); 73 hql.append(key); 74 hql.append(" = :"); 75 hql.append(key); 76 } 77 } 78 Query query = this.getSession().createQuery(hql.toString()); 79 if (null != params) { 80 query.setProperties(params); 81 } 82 return query.list(); 83 } 84 85 @Override 86 public List<T> find(String hql, Map<String, Object> params) { 87 Query query = this.getSession().createQuery(hql.toString()); 88 if (null != params) { 89 query.setProperties(params); 90 } 91 return query.list(); 92 } 93 94 @Override 95 public PageList<T> findByPage(int pageIndex, int pageSize, Map<String, Object> params) { 96 StringBuffer hql = new StringBuffer("from "); 97 hql.append(entityClass.getName()); 98 hql.append(" where 1 = 1 "); 99 if (null != params) { 100 for (String key : params.keySet()) { 101 hql.append(" and "); 102 hql.append(key); 103 hql.append(" = :"); 104 hql.append(key); 105 } 106 } 107 Query query = this.getSession().createQuery(hql.toString()); 108 if (null != params) { 109 query.setProperties(params); 110 } 111 112 //查询总条数 113 Query queryTotal = this.getSession().createQuery("select count(*)" + hql.toString()); 114 if (null != params) { 115 queryTotal.setProperties(params); 116 } 117 int total = Integer.parseInt(queryTotal.uniqueResult().toString()); 118 119 //设置分页 120 query.setFirstResult((pageIndex - 1) * pageSize); 121 query.setMaxResults(pageSize); 122 return new PageList<T>(query.list(), pageIndex, pageSize, total); 123 } 124 125 /* (non-Javadoc) 126 * @see com.Elastic.HibernateDemo3.ivy.dao.IBaseDao#findByNamed(java.lang.String, java.util.Map) 127 */ 128 @Override 129 public List<T> findByNamed(String queryName, Map<String, Object> params) { 130 Query query = this.getSession().getNamedQuery(queryName); 131 return query.setProperties(params).list(); 132 } 133 }
c.DeptDao
1 package com.Elastic.HibernateDemo3.ivy.dao; 2 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 3 public interface DeptDao extends IBaseDao<Dept>{ 4 5 }
d.EmpDao
1 package com.Elastic.HibernateDemo3.ivy.dao; 2 import java.util.List; 3 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 4 public interface EmpDao extends IBaseDao<Emp> { 5 List<Emp> findEmp(); 6 }
6.dao.impl包
a.DeptDaoImpl
1 package com.Elastic.HibernateDemo3.ivy.dao.impl; 2 import com.Elastic.HibernateDemo3.ivy.dao.BaseDao; 3 import com.Elastic.HibernateDemo3.ivy.dao.DeptDao; 4 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 5 public class DeptDaoImpl extends BaseDao<Dept> implements DeptDao { 6 7 }
b.EmpDaoImpl
1 package com.Elastic.HibernateDemo3.ivy.dao.impl; 2 import java.io.Serializable; 3 import java.util.List; 4 import java.util.Map; 5 import com.Elastic.HibernateDemo3.ivy.dao.BaseDao; 6 import com.Elastic.HibernateDemo3.ivy.dao.EmpDao; 7 import com.Elastic.HibernateDemo3.ivy.entity.Emp; 8 public class EmpDaoImpl extends BaseDao<Emp> implements EmpDao { 9 10 /* (non-Javadoc) 11 * @see com.Elastic.HibernateDemo3.ivy.dao.EmpDao#findEmp() 12 */ 13 @Override 14 public List<Emp> findEmp() { 15 this.getSession().getNamedQuery("findEmp"); //配置文件中命名查询的name值 16 return null; 17 } 18 }
7.service包
a.DeptService
1 package com.Elastic.HibernateDemo3.ivy.service; 2 import java.util.List; 3 import java.util.Map; 4 import com.Elastic.HibernateDemo3.ivy.common.PageList; 5 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 6 public interface DeptService{ 7 List<Dept> searchALLDept(); 8 9 List<Dept> searchDeptsByName(String name); 10 11 List<Dept> searchDeptByCondition(Map<String, Object> condition); 12 13 PageList<Dept> searchDeptByPage(int pageIndex, int pageSize, Map<String, Object> condition); 14 }
8.service.impl包
a.DeptServiceImpl
1 package com.Elastic.HibernateDemo3.ivy.service.impl; 2 import java.util.HashMap; 3 import java.util.List; 4 import java.util.Map; 5 import com.Elastic.HibernateDemo3.ivy.common.PageList; 6 import com.Elastic.HibernateDemo3.ivy.dao.DeptDao; 7 import com.Elastic.HibernateDemo3.ivy.dao.impl.DeptDaoImpl; 8 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 9 import com.Elastic.HibernateDemo3.ivy.service.DeptService; 10 public class DeptServiceImpl implements DeptService { 11 12 private DeptDao deptDao = new DeptDaoImpl(); 13 14 /* 15 * (non-Javadoc) 16 * 17 * @see com.Elastic.HibernateDemo3.ivy.service.DeptService#searchALLDept() 18 */ 19 @Override 20 public List<Dept> searchALLDept() { 21 return deptDao.find(null); 22 } 23 24 /* 25 * (non-Javadoc) 26 * 27 * @see 28 * com.Elastic.HibernateDemo3.ivy.service.DeptService#searchDeptsByName(java 29 * .lang.String) 30 */ 31 @Override 32 public List<Dept> searchDeptsByName(String name) { 33 Map<String, Object> params = new HashMap<String,Object>(); 34 params.put("deptName", name); 35 36 return deptDao.find(params); 37 } 38 39 @Override 40 public List<Dept> searchDeptByCondition(Map<String, Object> condition) { 41 42 return deptDao.find(condition); 43 } 44 45 @Override 46 public PageList<Dept> searchDeptByPage(int pageIndex, int pageSize, Map<String, Object> condition) { 47 return deptDao.findByPage(pageIndex, pageSize, condition); 48 } 49 }
9.servlet包
a.DeptServlet
1 package com.Elastic.HibernateDemo3.ivy.controller; 2 import java.io.IOException; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import com.Elastic.HibernateDemo3.ivy.entity.Dept; 11 import com.Elastic.HibernateDemo3.ivy.service.DeptService; 12 import com.Elastic.HibernateDemo3.ivy.service.impl.DeptServiceImpl; 13 /** 14 * Servlet implementation class DeptServlet 15 */ 16 public class DeptServlet extends HttpServlet { 17 private static final long serialVersionUID = 1L; 18 19 /** 20 * @see HttpServlet#HttpServlet() 21 */ 22 public DeptServlet() { 23 super(); 24 // TODO Auto-generated constructor stub 25 } 26 27 /** 28 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 29 */ 30 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 31 String oper = request.getParameter("oper"); 32 DeptService deptService = new DeptServiceImpl(); 33 switch (oper) { 34 case "all": 35 List<Dept> depts = deptService.searchALLDept(); 36 request.setAttribute("depts", depts); 37 38 //转发 39 request.getRequestDispatcher("/dept.jsp").forward(request, response); 40 break; 41 case "byName": 42 request.setAttribute("depts", deptService.searchDeptsByName(request.getParameter("name"))); 43 44 //转发 45 request.getRequestDispatcher("/dept.jsp").forward(request, response); 46 break; 47 case "byCondition": 48 //获取页面提交的参数 49 String deptName = request.getParameter("deptName"); 50 String location = request.getParameter("location"); 51 String id = request.getParameter("deptId"); 52 53 //创建保存参数的map集合 54 Map<String, Object> condition = new HashMap<String, Object>(); 55 if (null != deptName && deptName.trim().length() != 0) { 56 //【属性名和页面参数一样要写对!!!】 57 condition.put("deptName", deptName); 58 } 59 if (null != location && location.trim().length() != 0) { 60 //【属性名和页面参数一样要写对!!!】 61 condition.put("location", location); 62 } 63 if (null != id && id.trim().length() != 0) { 64 //【属性名和页面参数一样要写对!!!】 65 condition.put("deptId", Integer.parseInt(id)); 66 } 67 68 String pageIndexString = request.getParameter("pageIndex"); 69 String pageSizeString = request.getParameter("pageSize"); 70 71 int pageIndex = 1; 72 int pageSize = 2; 73 74 if (pageIndexString != null && pageIndexString.trim().length() != 0) { 75 pageIndex = Integer.parseInt(pageIndexString); 76 } 77 78 if (pageSizeString != null && pageSizeString.trim().length() != 0) { 79 pageSize = Integer.parseInt(pageSizeString); 80 } 81 82 request.setAttribute("pageList", deptService.searchDeptByPage(pageIndex, pageSize, condition)); 83 84 //转发 85 request.getRequestDispatcher("/dept.jsp").forward(request, response); 86 break; 87 88 default: 89 break; 90 } 91 } 92 93 /** 94 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 95 */ 96 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 97 this.doGet(request, response); 98 } 99 }
10.common包
a.PageList
1 package com.Elastic.HibernateDemo3.ivy.common; 2 import java.util.List; 3 public class PageList<T> { 4 private List<T> data; 5 private Integer pageIndex; 6 private Integer pageSize; 7 private Integer total; 8 private Integer pageTotal; 9 private Boolean next; 10 private Boolean prev; 11 12 public PageList(List<T> data, Integer pageIndex, Integer pageSize, Integer total) { 13 super(); 14 this.data = data; 15 this.pageIndex = pageIndex; 16 this.pageSize = pageSize; 17 this.total = total; 18 19 this.pageTotal = (int)Math.ceil((double)total / pageSize); 20 this.next = this.pageIndex < this.pageTotal; 21 this.prev = this.pageIndex > 1; 22 } 23 24 public List<T> getData() { 25 return data; 26 } 27 public Integer getPageIndex() { 28 return pageIndex; 29 } 30 public Integer getPageSize() { 31 return pageSize; 32 } 33 public Integer getTotal() { 34 return total; 35 } 36 public Integer getPageTotal() { 37 return pageTotal; 38 } 39 public Boolean getNext() { 40 return next; 41 } 42 public Boolean getPrev() { 43 return prev; 44 } 45 }
11.jsp
a.dept.jsp
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"> 24 <label>部门编号</label> 25 <input name="deptId" type="text"/> 26 <label>部门名称</label> 27 <!-- name与Dept类的属性名一样 --> 28 <input name="deptName" type="text"/> 29 <label>部门位置</label> 30 <input name="location" type="text"/> 31 32 <input type="hidden" name="pageIndex" value="1"/> 33 34 <input type="submit" value="搜索" data-toggle="search"/> 35 </form> 36 </div> 37 38 <table class="table table-bordered"> 39 <thead> 40 <tr> 41 <td>部门编号</td> 42 <td>部门名称</td> 43 <td>部门位置</td> 44 <td>操作</td> 45 </tr> 46 </thead> 47 <tbody> 48 <c:forEach items="${requestScope.pageList.data }" var="dept"> 49 <tr> 50 <td>${dept.deptId }</td> 51 <td>${dept.deptName }</td> 52 <td>${dept.location }</td> 53 <td><a class="btn btn-primary btn-xs" href="javascript:;">删除</a></td> 54 </tr> 55 56 </c:forEach> 57 </tbody> 58 </table> 59 <div class="panel-footer"> 60 <nav> 61 <ul id="deptPage" class="pagination" style="margin: 0px;"> 62 <li <c:if test="${not requestScope.pageList.prev }">class="disabled"</c:if>> 63 <a href="#" aria-label="Previous" > 64 <span aria-hidden="true">«</span> 65 </a> 66 </li> 67 <c:forEach begin="1" end="${requestScope.pageList.pageTotal }" step="1" varStatus="status"> 68 <li <c:if test="${status.index eq requestScope.pageList.pageIndex}">class="active"</c:if>> 69 <a href="#">${status.index }</a> 70 </li> 71 </c:forEach> 72 <li <c:if test="${not requestScope.pageList.next }">class="disabled"</c:if>> 73 <a href="#" aria-label="Next"> 74 <span aria-hidden="true">»</span> 75 </a> 76 </li> 77 </ul> 78 <div class="pull-right" style="line-height: 34px;">当前第${requestScope.pageList.pageIndex }页,总共${requestScope.pageList.pageTotal }页</div> 79 </nav> 80 </div> 81 </div> 82 83 </div> 84 85 <!-- 引用外部JS文件 --> 86 <script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-2.2.4.js"></script> 87 <script type="text/javascript" src="<%=request.getContextPath() %>/js/bootstrap.min.js"></script> 88 89 <script type="text/javascript"> 90 $(function() { 94 95 $(‘#deptPage‘).on(‘click‘,‘li > a‘, function() { 96 if ($(this).closest(‘li‘).hasClass(‘disabled‘)) { 97 return; 98 } 99 var pageIndex; 100 if ($(this).attr(‘aria-label‘) == ‘Previous‘) { 101 pageIndex = parseInt($(‘#deptPage > li.active > a‘).text()) - 1; 102 } else if ($(this).attr(‘aria-label‘) == ‘Next‘) { 103 pageIndex = parseInt($(‘#deptPage > li.active > a‘).text()) + 1; 104 } else { 105 pageIndex = $(this).text(); 106 } 107 $(‘[name="pageIndex"]‘).val(pageIndex); 108 $(‘[data-toggle="search"]‘).trigger(‘click‘); 109 }); 110 }); 111 </script> 112 113 </body> 114 </html>
标签:
原文地址:http://www.cnblogs.com/ivy-xu/p/5596780.html