==================================投影(查询)=============================
投影查询:查询一个持久化类的一个或多个属性值
1.将每条查询结果封装成Object对象
2.将每条查询结果封装成Object数组
3.将每条查询结果通过构造函数封装成对象
范例1:java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.Elastic.HibernateDemo3.ivy.entity.Dept
[L:数组
package com.Elastic.HibernateDemo3.ivy.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession(); String hql = "select deptName,location from Dept"; Query query = session.createQuery(hql); //2.将每条查询结果封装成Object数组
List<Dept> depts = query.list();
for (Dept dept : depts) {
System.out.println(dept.getDeptName());
}
}
}
范例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]
package com.Elastic.HibernateDemo3.ivy.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession(); //3.将每条查询结果通过构造函数封装成对象
String hql = "select new Dept[deptName,location] from Dept"; Query query = session.createQuery(hql); List<Dept> depts = query.list();
for (Dept dept : depts) {
System.out.println(dept.getDeptName());
}
}
}
范例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]
package com.Elastic.HibernateDemo3.ivy.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession(); String hql = "select new Dept[deptName,location] from Dept"; Query query = session.createQuery(hql); //2.将每条查询结果封装成Object数组
<Object> objs = query.list();
for (Object object : objs) {
System.out.println(object);
}
}
}
范例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]
package com.Elastic.HibernateDemo3.ivy.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
//将每条查询结果封装成Object数组与将每条查询结果通过构造函数封装成对象只能选其一???
String hql = "select new Dept[deptName,location] from Dept";
Query query = session.createQuery(hql);
List<Object[]> depts = query.list();
for (Object[] objects : depts) {
System.out.println(objects[0].toString() + objects[1]);
}
}
}
正确范例:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
String hql = "select deptName,location from Dept";
Query query = session.createQuery(hql);
List<Object[]> depts = query.list();
for (Object[] objects : depts) {
System.out.println(objects[0].toString() + objects[1]);
}
}
}
========================================分页查询===============================================
范例:
package com.Elastic.HibernateDemo3.ivy.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
String hql = "from Dept";
Query query = session.createQuery(hql); //当前页码
int pageIndex = 1;
//每页显示的条数
int pageSize = 2; //设置查询的起始位置
query.setFirstResult((pageIndex - 1) * pageSize);
//设置每页查询的(最大)条数
query.setMaxResults(pageSize); List<Dept> depts = query.list();
for (Dept dept : depts) {
System.out.println(dept.getDeptName());
}
}
}
==================================连接查询==============================
内联:只显示互相有值的两表
左外联:左边全部显示,右边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
迫切连接???
package com.Elastic.HibernateDemo3.ivy.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
String hql = "from Emp emp inner join emp.dept";
List<Emp> emps = session.createQuery(hql).list();
for (Emp emp : emps) {
System.out.println(emp.getEmpName() + emp.getDept().getDeptName());
}
}
}
正确范例:
package com.Elastic.HibernateDemo3.ivy.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
String hql = "from Emp emp inner join emp.dept";
List<Emp> emps = session.createQuery(hql).list();
for (Emp emp : emps) {
System.out.println(emp.getEmpName() + emp.getDept().getDeptName());
}
}
}
===================================子查询================================
子查询语句:应用在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:
package com.Elastic.HibernateDemo3.ivy.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Session session = HibernateUtil.getSession();
//直接创建SQL
String sql = "select e.*,d.* from emp e inner join dept d on e.deptId = d.deptId"; //创建SQLQuery对象,命名查询createSQLQuery()
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addEntity(Emp.class); List<Emp> emps = sqlQuery.list();
for (Emp emp : emps) {
System.out.println(emp.getEmpName() + emp.getDept().getDeptName());
} //':name' 相当 SQL语句中的 '?'。其他like等语法HQL一样用
Query query = session
.createSQLQuery(
"select * from Emp where empName like :ename and Job = :job")
.addEntity(Emp.class).setString("ename", "%张%")
.setString("job", "工程师");
List<Emp> list = query.list();
}
}
=================================命名查询=========================
命名查询语句:在映射文件中定义★字符串形式★的查询语句
HQL查询语句的命名查询,存在★***.hbm.xml★
HQL命名查询
SQL命名查询
【技巧:表单 传入两个值name和value。所以 命名时,用Map做】
范例1:
<hibernate-mapping>
<class name="com.xuetang9.demo.entity.Emp" table="emp">
......
</class>
<query name="findEmpByJob">
<![CDATA[
from Emp e where e.job = :job
]]>
</query>
</hibernate-mapping>
范例2:
1.Emp.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.Elastic.HibernateDemo3.ivy.entity.Emp" table="emp"> <!-- 主键UID(唯一标识) -->
<id name="empNo" column="empNo"><!-- column单独一行,属性更全 --> <!-- 主键生成策略:increment,assigned,native等 -->
<generator class="increment"></generator>
</id> <!-- 属性名(★★setDeptName★★):数据库表字段(如果是关键字,用``标志) -->
<property name="empName" column="empName"></property> <!-- 这个字段进行新增和修改功能,要被Hibernate忽略。因为,与外键一样 -->
<property name="deptId" column="deptId" insert="false" update="false"></property> <!-- 多对一的关系(多个员工属于一个部门) -->
<many-to-one name="dept" class="com.Elastic.HibernateDemo3.ivy.entity.Dept" column="deptId" lazy="proxy"></many-to-one>
<!-- fetch存在,懒加载没用。fetch不放在配置文件中 --> </class> <!-- 配置HQL命名查询 -->
<query name="findEmpByDeptName">
<!-- 文本 -->
<![CDATA[
from Emp e where e.dept.deptName = :deptname and e.empName = :ename
]]>
</query> <!-- 配置原生的SQL语句 -->
<sql-query name="findEmp">
<return alias="e" class="com.Elastic.HibernateDemo3.ivy.entity.Emp"></return>
select * from emp e inner join dept d on e.deptId = d.deptId where e.empName = :ename and d.deptName = :deptname
</sql-query>
</hibernate-mapping>
2.Test类
package com.Elastic.HibernateDemo3.ivy.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
String name = "findEmp";
//String name = "findEmpByDeptName";
Map<String, Object> params = new HashMap<String, Object>();
params.put("deptname", "销售部");
params.put("ename", "李四"); Session session = HibernateUtil.getSession();
Query query = session.getNamedQuery(name);
query.setProperties(params);
List<Emp> emps = query.list();
for (Emp emp : emps) {
System.out.println(emp.getEmpName() + emp.getDept().getDeptName());
}
}
}
=================================综合范例==============================
1.实体类及其hbm.xml文件 -- entity包
a.Dept
package com.Elastic.HibernateDemo3.ivy.entity;
import java.io.Serializable;
import java.util.Set;
public class Dept implements Serializable {
private static final long serialVersionUID = 2261199233032137882L;
private Integer deptId;
private String deptName;
private String location; //多对一:一个部门有多个员工
//set:唯一
private Set<Emp> emps; public Set<Emp> getEmps() {
return emps;
}
public void setEmps(Set<Emp> emps) {
this.emps = emps;
} public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
b.Dept.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.Elastic.HibernateDemo3.ivy.entity.Dept" table="dept">
<!-- 主键OID(唯一标识) -->
<id name="deptId" column="deptid"><!-- column单独一行,属性更全 -->
<!-- 主键生成策略:increment,assigned,native等 -->
<generator class="increment"></generator>
</id> <!-- 属性名(★★setDeptName★★):数据库表字段(如果是关键字,用``标志) -->
<property name="deptName" column="deptname"></property>
<property name="location" column="location"></property> <!-- 多个员工 -->
<!-- <set name="emps" cascade="save-update"> --><!-- 新增部门的同时,新增员工(级联操作) -->
<!-- <set name="emps" cascade="all" inverse="true" order-by="empNo desc"> --><!-- 删除部门同时删除员工 -->
<set name="emps" cascade="all" inverse="true" order-by="empNo desc" lazy="extra"><!-- 删除部门同时删除员工
表dept中deptid -->
<key column="deptid"></key>
<one-to-many class="com.Elastic.HibernateDemo3.ivy.entity.Emp"></one-to-many>
</set> </class>
</hibernate-mapping>
a1.Emp
package com.Elastic.HibernateDemo3.ivy.entity;
import java.io.Serializable;
public class Emp implements Serializable {
/**
* <p>
* <h3>作用:</h3>
* </p>
* @see long
* @see serialVersionUID
*/
private static final long serialVersionUID = -6182713107749938132L;
private Integer empNo;
private String empName;
private Integer deptId; private Dept dept; public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public Integer getEmpNo() {
return empNo;
}
public void setEmpNo(Integer empNo) {
this.empNo = empNo;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
}
b1.Emp.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.Elastic.HibernateDemo3.ivy.entity.Emp" table="emp"> <!-- 主键UID(唯一标识) -->
<id name="empNo" column="empNo"><!-- column单独一行,属性更全 --> <!-- 主键生成策略:increment,assigned,native等 -->
<generator class="increment"></generator>
</id> <!-- 属性名(★★setDeptName★★):数据库表字段(如果是关键字,用``标志) -->
<property name="empName" column="empName"></property> <!-- 这个字段进行新增和修改功能,要被Hibernate忽略。因为,与外键一样 -->
<property name="deptId" column="deptId" insert="false" update="false"></property> <!-- 多对一的关系(多个员工属于一个部门) -->
<many-to-one name="dept" class="com.Elastic.HibernateDemo3.ivy.entity.Dept" column="deptId" lazy="proxy"></many-to-one>
<!-- fetch存在,懒加载没用。fetch不放在配置文件中 --> </class> <!-- 配置HQL命名查询 -->
<query name="findEmpByDeptName">
<!-- 文本 -->
<![CDATA[
from Emp e where e.dept.deptName = :deptname and e.empName = :ename
]]>
</query> <!-- 配置原生的SQL语句 -->
<sql-query name="findEmp">
<return alias="e" class="com.Elastic.HibernateDemo3.ivy.entity.Emp"></return> select * from emp e inner join dept d on e.deptId = d.deptId where e.empName = :ename and d.deptName = :deptname
</sql-query>
</hibernate-mapping>
2.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>
<!-- 1.连接数据库 -->
<!-- 连接数据库名 -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property> <!-- 连接数据库的用户名 -->
<property name="connection.username">root</property> <!-- 连接数据库的密码 -->
<property name="connection.password">root</property> <!-- 数据库驱动类 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 2.数据库方言(不同的数据库) -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- 3.其他属性 -->
<!-- 是否显示sql语句 -->
<property name="show_sql">true</property>
<!-- 是否显示格式化sql语句,如果要显示,★★★一定要先显示show_sql语句★★★ -->
<property name="format_sql">true</property> <!-- 4.数据库对应的实体类的映射文件路径 -->
<mapping resource="com/Elastic/HibernateDemo3/ivy/entity/Dept.hbm.xml"></mapping>
<mapping resource="com/Elastic/HibernateDemo3/ivy/entity/Emp.hbm.xml"></mapping>
</session-factory>
</hibernate-configuration>
3.util包:HibernateUtil
package com.Elastic.HibernateDemo3.ivy.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public final class HibernateUtil {
private static Configuration cfg = null;
private static SessionFactory sessionFactory = null; //本地线程
public static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); static{
cfg = new Configuration().configure();
sessionFactory = cfg.buildSessionFactory();
} public static Session getSession(){
Session session = threadLocal.get();
if (null == session || !session.isOpen()) {
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
}
4.filter包
a.EncodingFilter
package com.Elastic.HibernateDemo3.ivy.filter;
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 EncodingFilter implements Filter { /* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
@Override
public void destroy() {
// TODO Auto-generated method stub } /* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
} /* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub }
}
b.OpenSessionInViewFilter
package com.Elastic.HibernateDemo3.ivy.filter;
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;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil;
public class OpenSessionInViewFilter implements Filter{ /* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
@Override
public void destroy() {
// TODO Auto-generated method stub } /* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException { /* 事务以及session的关闭 */ //获取session
Session session = HibernateUtil.getSession();
//开启事务
Transaction tx = session.beginTransaction(); try {
chain.doFilter(request, response);
//提交事务
tx.commit();
} catch (HibernateException e) {
tx.rollback();
e.printStackTrace();
} finally {
//关闭session
session.close();
}
} /* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub }
}
5.dao包
a.IBaseDao
package com.Elastic.HibernateDemo3.ivy.dao;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import com.Elastic.HibernateDemo3.ivy.common.PageList;
public interface IBaseDao<T> {
void save(T record); //不明确id的类型,就用Serializable
void delete(Serializable id); void update(T record); T findById(Serializable id); List<T> find(Map<String, Object> params); List<T> find(String hql,Map<String, Object> params); PageList<T> findByPage(int pageIndex, int pageSize, Map<String, Object> params); List<T> findByNamed(String queryName, Map<String, Object> params);
}
b.BaseDao
package com.Elastic.HibernateDemo3.ivy.dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.Session;
import com.Elastic.HibernateDemo3.ivy.common.PageList;
import com.Elastic.HibernateDemo3.ivy.util.HibernateUtil; //忽略警告
@SuppressWarnings({ "rawtypes", "unchecked" })
public class BaseDao<T> implements IBaseDao<T>{ private Class entityClass; public BaseDao(){
entityClass = this.getEntityClass();
} /**
*
* <p>
* <h3>方法功能描述:根据反射得到实体类的类型</h3>
* </p>
* @return
* @procedure 执行过程
* @see BaseDao
*/
private Class getEntityClass(){
try {
ParameterizedType paramsType = (ParameterizedType)this.getClass().getGenericSuperclass();
return (Class)paramsType.getActualTypeArguments()[0];
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public Session getSession(){
return HibernateUtil.getSession();
} @Override
public void save(T record){
this.getSession().save(record);
} @Override
public void delete(Serializable id){
this.getSession().delete(this.findById(id));
} @Override
public void update(T record){
this.getSession().update(record);
} @Override
public T findById(Serializable id){
return (T)this.getSession().get(entityClass, id);
} @Override
public List<T> find(Map<String, Object> params){
StringBuffer hql = new StringBuffer("from ");
hql.append(entityClass.getName());
hql.append(" where 1 = 1 ");
if (null != params) {
for (String key : params.keySet()) {
hql.append(" and ");
hql.append(key);
hql.append(" = :");
hql.append(key);
}
}
Query query = this.getSession().createQuery(hql.toString());
if (null != params) {
query.setProperties(params);
}
return query.list();
} @Override
public List<T> find(String hql, Map<String, Object> params) {
Query query = this.getSession().createQuery(hql.toString());
if (null != params) {
query.setProperties(params);
}
return query.list();
} @Override
public PageList<T> findByPage(int pageIndex, int pageSize, Map<String, Object> params) {
StringBuffer hql = new StringBuffer("from ");
hql.append(entityClass.getName());
hql.append(" where 1 = 1 ");
if (null != params) {
for (String key : params.keySet()) {
hql.append(" and ");
hql.append(key);
hql.append(" = :");
hql.append(key);
}
}
Query query = this.getSession().createQuery(hql.toString());
if (null != params) {
query.setProperties(params);
} //查询总条数
Query queryTotal = this.getSession().createQuery("select count(*)" + hql.toString());
if (null != params) {
queryTotal.setProperties(params);
}
int total = Integer.parseInt(queryTotal.uniqueResult().toString()); //设置分页
query.setFirstResult((pageIndex - 1) * pageSize);
query.setMaxResults(pageSize);
return new PageList<T>(query.list(), pageIndex, pageSize, total);
} /* (non-Javadoc)
* @see com.Elastic.HibernateDemo3.ivy.dao.IBaseDao#findByNamed(java.lang.String, java.util.Map)
*/
@Override
public List<T> findByNamed(String queryName, Map<String, Object> params) {
Query query = this.getSession().getNamedQuery(queryName);
return query.setProperties(params).list();
}
}
c.DeptDao
package com.Elastic.HibernateDemo3.ivy.dao;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
public interface DeptDao extends IBaseDao<Dept>{ }
d.EmpDao
package com.Elastic.HibernateDemo3.ivy.dao;
import java.util.List;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
public interface EmpDao extends IBaseDao<Emp> {
List<Emp> findEmp();
}
6.dao.impl包
a.DeptDaoImpl
package com.Elastic.HibernateDemo3.ivy.dao.impl;
import com.Elastic.HibernateDemo3.ivy.dao.BaseDao;
import com.Elastic.HibernateDemo3.ivy.dao.DeptDao;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
public class DeptDaoImpl extends BaseDao<Dept> implements DeptDao { }
b.EmpDaoImpl
package com.Elastic.HibernateDemo3.ivy.dao.impl;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import com.Elastic.HibernateDemo3.ivy.dao.BaseDao;
import com.Elastic.HibernateDemo3.ivy.dao.EmpDao;
import com.Elastic.HibernateDemo3.ivy.entity.Emp;
public class EmpDaoImpl extends BaseDao<Emp> implements EmpDao { /* (non-Javadoc)
* @see com.Elastic.HibernateDemo3.ivy.dao.EmpDao#findEmp()
*/
@Override
public List<Emp> findEmp() {
this.getSession().getNamedQuery("findEmp"); //配置文件中命名查询的name值
return null;
}
}
7.service包
a.DeptService
package com.Elastic.HibernateDemo3.ivy.service;
import java.util.List;
import java.util.Map;
import com.Elastic.HibernateDemo3.ivy.common.PageList;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
public interface DeptService{
List<Dept> searchALLDept(); List<Dept> searchDeptsByName(String name); List<Dept> searchDeptByCondition(Map<String, Object> condition); PageList<Dept> searchDeptByPage(int pageIndex, int pageSize, Map<String, Object> condition);
}
8.service.impl包
a.DeptServiceImpl
package com.Elastic.HibernateDemo3.ivy.service.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.Elastic.HibernateDemo3.ivy.common.PageList;
import com.Elastic.HibernateDemo3.ivy.dao.DeptDao;
import com.Elastic.HibernateDemo3.ivy.dao.impl.DeptDaoImpl;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
import com.Elastic.HibernateDemo3.ivy.service.DeptService;
public class DeptServiceImpl implements DeptService { private DeptDao deptDao = new DeptDaoImpl(); /*
* (non-Javadoc)
*
* @see com.Elastic.HibernateDemo3.ivy.service.DeptService#searchALLDept()
*/
@Override
public List<Dept> searchALLDept() {
return deptDao.find(null);
} /*
* (non-Javadoc)
*
* @see
* com.Elastic.HibernateDemo3.ivy.service.DeptService#searchDeptsByName(java
* .lang.String)
*/
@Override
public List<Dept> searchDeptsByName(String name) {
Map<String, Object> params = new HashMap<String,Object>();
params.put("deptName", name); return deptDao.find(params);
} @Override
public List<Dept> searchDeptByCondition(Map<String, Object> condition) { return deptDao.find(condition);
} @Override
public PageList<Dept> searchDeptByPage(int pageIndex, int pageSize, Map<String, Object> condition) {
return deptDao.findByPage(pageIndex, pageSize, condition);
}
}
9.servlet包
a.DeptServlet
package com.Elastic.HibernateDemo3.ivy.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Elastic.HibernateDemo3.ivy.entity.Dept;
import com.Elastic.HibernateDemo3.ivy.service.DeptService;
import com.Elastic.HibernateDemo3.ivy.service.impl.DeptServiceImpl;
/**
* Servlet implementation class DeptServlet
*/
public class DeptServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public DeptServlet() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String oper = request.getParameter("oper");
DeptService deptService = new DeptServiceImpl();
switch (oper) {
case "all":
List<Dept> depts = deptService.searchALLDept();
request.setAttribute("depts", depts); //转发
request.getRequestDispatcher("/dept.jsp").forward(request, response);
break;
case "byName":
request.setAttribute("depts", deptService.searchDeptsByName(request.getParameter("name"))); //转发
request.getRequestDispatcher("/dept.jsp").forward(request, response);
break;
case "byCondition":
//获取页面提交的参数
String deptName = request.getParameter("deptName");
String location = request.getParameter("location");
String id = request.getParameter("deptId"); //创建保存参数的map集合
Map<String, Object> condition = new HashMap<String, Object>();
if (null != deptName && deptName.trim().length() != 0) {
//【属性名和页面参数一样要写对!!!】
condition.put("deptName", deptName);
}
if (null != location && location.trim().length() != 0) {
//【属性名和页面参数一样要写对!!!】
condition.put("location", location);
}
if (null != id && id.trim().length() != 0) {
//【属性名和页面参数一样要写对!!!】
condition.put("deptId", Integer.parseInt(id));
} String pageIndexString = request.getParameter("pageIndex");
String pageSizeString = request.getParameter("pageSize"); int pageIndex = 1;
int pageSize = 2; if (pageIndexString != null && pageIndexString.trim().length() != 0) {
pageIndex = Integer.parseInt(pageIndexString);
} if (pageSizeString != null && pageSizeString.trim().length() != 0) {
pageSize = Integer.parseInt(pageSizeString);
} request.setAttribute("pageList", deptService.searchDeptByPage(pageIndex, pageSize, condition)); //转发
request.getRequestDispatcher("/dept.jsp").forward(request, response);
break; default:
break;
}
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
10.common包
a.PageList
package com.Elastic.HibernateDemo3.ivy.common;
import java.util.List;
public class PageList<T> {
private List<T> data;
private Integer pageIndex;
private Integer pageSize;
private Integer total;
private Integer pageTotal;
private Boolean next;
private Boolean prev; public PageList(List<T> data, Integer pageIndex, Integer pageSize, Integer total) {
super();
this.data = data;
this.pageIndex = pageIndex;
this.pageSize = pageSize;
this.total = total; this.pageTotal = (int)Math.ceil((double)total / pageSize);
this.next = this.pageIndex < this.pageTotal;
this.prev = this.pageIndex > 1;
} public List<T> getData() {
return data;
}
public Integer getPageIndex() {
return pageIndex;
}
public Integer getPageSize() {
return pageSize;
}
public Integer getTotal() {
return total;
}
public Integer getPageTotal() {
return pageTotal;
}
public Boolean getNext() {
return next;
}
public Boolean getPrev() {
return prev;
}
}
11.jsp
a.dept.jsp
<%-- 引入JSP页面PAGE指令 --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- 引入JSTL标签指令 --%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html language="zh-CN">
<head>
<meta charset="utf-8">
<!-- 设置浏览器渲染的引擎 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<!-- 设置支持移动设备 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>网页标题</title>
<!-- 引用bootstrap样式 -->
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
<div class="panel panel-primary">
<div class="panel-heading"><span class="h3">部门信息</span></div>
<div class="panel-body">
<form action="<%=request.getContextPath()%>/dept/search?oper=byCondition" method="post">
<label>部门编号</label>
<input name="deptId" type="text"/>
<label>部门名称</label>
<!-- name与Dept类的属性名一样 -->
<input name="deptName" type="text"/>
<label>部门位置</label>
<input name="location" type="text"/> <input type="hidden" name="pageIndex" value="1"/> <input type="submit" value="搜索" data-toggle="search"/>
</form>
</div> <table class="table table-bordered">
<thead>
<tr>
<td>部门编号</td>
<td>部门名称</td>
<td>部门位置</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<c:forEach items="${requestScope.pageList.data }" var="dept">
<tr>
<td>${dept.deptId }</td>
<td>${dept.deptName }</td>
<td>${dept.location }</td>
<td><a class="btn btn-primary btn-xs" href="javascript:;">删除</a></td>
</tr> </c:forEach>
</tbody>
</table>
<div class="panel-footer">
<nav>
<ul id="deptPage" class="pagination" style="margin: 0px;">
<li <c:if test="${not requestScope.pageList.prev }">class="disabled"</c:if>>
<a href="#" aria-label="Previous" >
<span aria-hidden="true">«</span>
</a>
</li>
<c:forEach begin="1" end="${requestScope.pageList.pageTotal }" step="1" varStatus="status">
<li <c:if test="${status.index eq requestScope.pageList.pageIndex}">class="active"</c:if>>
<a href="#">${status.index }</a>
</li>
</c:forEach>
<li <c:if test="${not requestScope.pageList.next }">class="disabled"</c:if>>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
<div class="pull-right" style="line-height: 34px;">当前第${requestScope.pageList.pageIndex }页,总共${requestScope.pageList.pageTotal }页</div>
</nav>
</div>
</div> </div> <!-- 引用外部JS文件 -->
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-2.2.4.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/bootstrap.min.js"></script> <script type="text/javascript">
$(function() { $('#deptPage').on('click','li > a', function() {
if ($(this).closest('li').hasClass('disabled')) {
return;
}
var pageIndex;
if ($(this).attr('aria-label') == 'Previous') {
pageIndex = parseInt($('#deptPage > li.active > a').text()) - 1;
} else if ($(this).attr('aria-label') == 'Next') {
pageIndex = parseInt($('#deptPage > li.active > a').text()) + 1;
} else {
pageIndex = $(this).text();
}
$('[name="pageIndex"]').val(pageIndex);
$('[data-toggle="search"]').trigger('click');
});
});
</script> </body>
</html>