==================================投影(查询)=============================
投影查询:查询一个持久化类的一个或多个属性值
    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">&laquo;</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">&raquo;</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>

Hibernate(四)的更多相关文章

  1. hibernate(四) 双向多对多映射关系

    序言 莫名长了几颗痘,真TM疼,可能是现在运动太少了,天天对着电脑,决定了,今天下午花两小时去跑步了, 现在继上一章节的一对多的映射关系讲解后,今天来讲讲多对多的映射关系把,明白了一对多,多对多个人感 ...

  2. Hibernate(四)之对象状态及一级缓存

    一.Hibernate中的对象状态 1.1.瞬时态(临时态) 没有与Hibernate产生关联 与数据库中的记录没有产生关联(有关联就是与数据库中表的id相对应) 获得:一般都只直接创建(new) 瞬 ...

  3. Hibernate(四)结构-基础语义和事务

    一.基础语义 核心: Configuration SessionFactory Session 二.Configuration Configuration类负责管理Hibernate的配置信息,Hib ...

  4. hibernate(四)__由表逆向创建Domain对象和对象关系映射文件

    之前我们是手写Domain对象和对象关系映射文件->然后生成数据库中的Table. 现在我们反过来先在数据库中建好Table->然后用工具生成Domain对象和对象关系映射文件. 步骤: ...

  5. Hibernate四 批量处理

    Hibernate批量处理一 批量插入将很多条记录插入数据库时,Hibernate通常会采用以下做法:public void test() { for(int i=0;i<1000;i++){ ...

  6. Hibernate(四)——缓存策略+lazy

    Hibernate作为和数据库数据打交道的框架,自然会设计到操作数据的效率问题,而对于一些频繁操作的数据,缓存策略就是提高其性能一种重要手段,而Hibernate框架是支持缓存的,而且支持一级和二级两 ...

  7. ORM框架Hibernate (四) 一对一单向、双向关联映射

    简介 在上一篇博客说了一下多对一映射,这里再说一下一对一关联映射,这种例子在生活中很常见,比如一个人的信息和他的身份证是一对一.又如一夫一妻制等等. 记得在Java编程思想上第一句话是“一切皆对象”, ...

  8. ssh架构之hibernate(四)二级缓存

    二级缓存使用步骤: 1.拷贝jar包 2.配置Hibernate.cfg.xml文件 a.#开启二级缓存 hibernate.cache.use_second_level_cache=true b.# ...

  9. Hibernate(四)--延迟加载(lazyload)

    hibernate中的延迟加载(lazyload)分属性的延迟加载和关系的延迟加载 属性的延迟加载: 当使用load的方式来获取对象的时候,只有访问了这个对象的属性,hibernate才会到数据库中进 ...

随机推荐

  1. 【题解】SDOI2015序列统计

    [题解]SDOI2015序列统计 来自永不AFO的YYB的推荐 这里是乘积,比较麻烦,不过由于给定的序列膜数是个小质数,所以可以\(O(m^2\log m)\)找原跟(实际上不需要这么多). 乘积有点 ...

  2. 【题解】有标号的DAG计数1

    [HZOI 2015] 有标号的DAG计数 I 设\(f_i\)为\(i\)个点时的DAG图,(不必联通) 考虑如何转移,由于一个DAG必然有至少一个出度为\(0\)的点,所以我们钦定多少个出度为\( ...

  3. .net core试水

    概述 大概记录下我如何第一次使用.net core搭建一个api,由于最近.net core比较火,我也尝试着使用.net core做了一个小功能 本文主要包括 1.环境配置 2.程序编写 3.程序部 ...

  4. (httpd、php)2

    (一)再说编译安装httpd2.4 新特性: 1:MPM(多处理模块)支持运行为DSO(动态共享,动态加载模式)机制,以模块形式按需加载,支持动态加载 2:event MPM生产环境可用 3:支持异步 ...

  5. java基础之----非空判断

    大家好,第一次写博客,一直想写博客,用于自我总结,也用于帮助新同学成长. 平常我们开发的时候,用到很多非空判断,但是很多同学用到的地方不是很准确,这里,我把自己平时遇到的坑跟大家说说.我废话不多,只想 ...

  6. docker概述和基本命令

    命名空间 Docker使用一种称为namespaces提供隔离工作空间的技术来称为容器.当您运行容器时,Docker会为该容器创建一组 名称空间. 这些命名空间提供了一层隔离.容器的每个方面都在一个单 ...

  7. python防止字符串转义

    部分转自:https://www.cnblogs.com/hellofengying/p/10183057.html 今天再打开文件名时,出现了错误,如下: In []: path='D:\Code\ ...

  8. 【转】python get-pip.py could not find a version that satisfies

    转:https://blog.csdn.net/yanlisuo/article/details/81357305 转:https://blog.csdn.net/dyrlovewc/article/ ...

  9. C++ | C++ 基础知识 | 指针、数组与引用

    1.指针 在 C++ 语言中存放及使用内存地址是通过指针和引用完成的. char c = 'a'; // 声明 c 变量,c 变量存储的是 'a' 的值. char* p = &c; // 声 ...

  10. 斯坦福算法分析和设计_2. 排序算法MergeSort

      Motivate MergeSort是个相对古老的算法了,为什么现在我们还要讨论这么古老的东西呢?有几个原因: 它虽然年龄很大了,但是在实践中一直被沿用,仍然是很多程序库中的标准算法之一. 实现它 ...