Hibernate(二)

Hibernate可以应用在任何使用JBDC的场合。
    1.Java的客户端程序使用
    2.Servlet或JSP的Web应用中使用

===========================关联映射==========================
种类:
    一对多(多对一)关联
    一对一关联
    多对多关联
方向:
    单向关联
    双向关联

1.单向一对多关联    
    步骤:
        1)持久化类中添加关联类的相关属性和getter/setter方法
        2)映射文件建立该属性和数据库表字段的映射信息
            <set>和<one-to-many>
            
<set>属性
name(必须存在)        
table
lazy        是否使用延迟加载及加载策略        true
fetch        抓取数据的策略                    select
inverse        维护方式                        false
    
2.单向多对一关联:
    步骤:
        1)持久化类中添加关联类的相关属性和getter/setter方法
        2)映射文件建立该属性和数据库表字段的映射信息
            <many-to-one>
            
<many-to-one>属性
name(必须存在)
class        完全限定名
column
not-null                                    false
lazy        是否使用延迟加载及加载策略        proxy
fetch        抓取数据的策略                    select

3.双向一对多关联
    同时配置单向一对多和单向多对一

4.一对一关联
    主键和外键、

步骤:
    1)持久化类中添加关联类的相关属性和getter/setter方法
    2)映射文件相关映射信息
        
5.多对多关联
    a.不创建中间表的持久化类。在映射文件中<many-to-many>
    b.创建中间表、两端数据库表的持久化类。针对中间表的持久化类分别和两端的数据库表的持久化类创建一对多关联(即多对多变成两个一对多)
        
属性:
    1.cascade:级联添加
        a.建立一对多关联
        b.在<set>标签中配置cascade属性
        
        cascade属性值     描述
            none        当Session操纵当前对象时,忽略其他关联的对象。它是cascade属性的默认值
            save-update    当通过Session的save()、update()及saveOrUpdate()方法来保存或更新当前对象时,级联保存所有关联的新建的瞬时状态的对象,并且级联更新所有关联的游离状态的对象。
            delete        当通过Session的delete()方法删除当前对象时,会级联删除所有关联的对象。
            all            包含save-update,delete的行为。
            
    2.inverse(<set>):指定了关联关系中的方向
        a.inverse设置为false,则为主动方,由主动方负责维护关联关系,默认是false 。
        b.inverse设置为true,不负责维护关联关系。
注意:delete(all)与    inverse 一起用

    3.order-by(<set>):数据库中对集合排序

=============================延迟加载=============================
定义:(lazy load懒加载)是当在真正需要数据时,才执行SQL语句进行查询。避免了无谓的性能开销。

查询策略:
    1.类级别的查询策略
        lazy属性值         加载策略
        true(默认)    延迟加载
        false            立即加载
        
    2.一对多和多对多关联的查询策略
        lazy属性值         加载策略
        true(默认)    延迟加载
        false            立即加载
        extra            加强延迟加载
        
    3.多对一关联的查询策略
        lazy属性值         加载策略
        proxy(默认)    延迟加载
        no-proxy        无代理延迟加载
        false            立即加载

范例:
1.hibernate.cfg.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <!-- 1.连接数据库 -->
 8         <!-- 连接数据库名 -->
 9         <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
10         
11         <!-- 连接数据库的用户名 -->
12         <property name="connection.username">root</property>
13         
14         <!-- 连接数据库的密码 -->
15         <property name="connection.password">root</property>
16         
17         <!-- 数据库驱动类 -->
18         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
19         
20         <!-- 2.数据库方言(不同的数据库) -->
21         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
22         
23         <!-- 3.其他属性 -->
24         <!-- 是否显示sql语句 -->
25         <property name="show_sql">true</property>
26         <!-- 是否显示格式化sql语句,如果要显示,★★★一定要先显示show_sql语句★★★ -->
27         <property name="format_sql">true</property>
28         
29         <!-- 4.数据库对应的实体类的映射文件路径 -->
30         <mapping resource="com/Elastic/HibernateDemo2/ivy/entity/Dept.hbm.xml"></mapping>
31         <mapping resource="com/Elastic/HibernateDemo2/ivy/entity/Emp.hbm.xml"></mapping>
32     </session-factory>
33 </hibernate-configuration>


2.Dept类和Dept.hbm.xml

 1 package com.Elastic.HibernateDemo2.ivy.entity;
 2 import java.io.Serializable;
 3 import java.util.Set;
 4 public class Dept implements Serializable {
 5     /**
 6      * <p>
 7      * <h3>作用:</h3>
 8      * </p>
 9      * @see long
10      * @see serialVersionUID
11      */
12     private static final long serialVersionUID = 2261199233032137882L;
13     private Integer deptId;
14     private String deptName;
15     private String location;
16     
17     //多对一:一个部门有多个员工
18     //set:唯一
19     private Set<Emp> emps;
20     
21     public Set<Emp> getEmps() {
22         return emps;
23     }
24     public void setEmps(Set<Emp> emps) {
25         this.emps = emps;
26     }
27     public Integer getDeptId() {
28         return deptId;
29     }
30     public void setDeptId(Integer deptId) {
31         this.deptId = deptId;
32     }
33     public String getDeptName() {
34         return deptName;
35     }
36     public void setDeptName(String deptName) {
37         this.deptName = deptName;
38     }
39     public String getLocation() {
40         return location;
41     }
42     public void setLocation(String location) {
43         this.location = location;
44     }
45 }
 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.HibernateDemo2.ivy.entity.Dept" table="dept">
 8     
 9         <!-- 主键OID(唯一标识) -->
10         <id name="deptId" column="deptid" lazy="false"><!-- column单独一行,属性更全 -->
11         
12             <!-- 主键生成策略:increment,assigned,native等 -->
13             <generator class="increment"></generator>
14         </id>
15         
16         <!-- 属性名(★★setDeptName★★):数据库表字段(如果是关键字,用``标志) -->
17         <property name="deptName" column="deptname"></property>
18         <property name="location" column="location"></property>
19         
20         <!-- 多个员工 -->
21         <!-- <set name="emps" cascade="save-update"> --><!-- 新增部门的同时,新增员工(级联操作) -->
22         <!-- <set name="emps" cascade="all" inverse="true" order-by="empNo desc"> --><!-- 删除部门同时删除员工 -->
23         <set name="emps" cascade="all" inverse="true" order-by="empNo desc" lazy="extra"><!-- 删除部门同时删除员工 -->
24             <!-- 表dept中deptid -->
25             <key column="deptid"></key>
26             <one-to-many class="com.Elastic.HibernateDemo2.ivy.entity.Emp"></one-to-many>
27         </set>    
28     </class>
29 </hibernate-mapping>        


3.Emp类和Emp.hbm.xml

 1 package com.Elastic.HibernateDemo2.ivy.entity;
 2 import java.io.Serializable;
 3 public class Emp implements Serializable {
 4     private static final long serialVersionUID = -6182713107749938132L;
 5     private Integer empNo;
 6     private String empName;
 7     private Integer deptId;
 8     
 9     private Dept dept;
10     
11     public Integer getDeptId() {
12         return deptId;
13     }
14     public void setDeptId(Integer deptId) {
15         this.deptId = deptId;
16     }
17     public Dept getDept() {
18         return dept;
19     }
20     public void setDept(Dept dept) {
21         this.dept = dept;
22     }
23     public Integer getEmpNo() {
24         return empNo;
25     }
26     public void setEmpNo(Integer empNo) {
27         this.empNo = empNo;
28     }
29     public String getEmpName() {
30         return empName;
31     }
32     public void setEmpName(String empName) {
33         this.empName = empName;
34     }
35 }
 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.HibernateDemo2.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.HibernateDemo2.ivy.entity.Dept" column="deptId" lazy="proxy"></many-to-one>
25         <!-- fetch存在,懒加载没用。fetch不放在配置文件中 -->
26     </class>
27 </hibernate-mapping>


4.Test类

  1 package com.Elastic.HibernateDemo2.ivy.test;
  2 import java.util.HashSet;
  3 import java.util.Set;
  4 import org.hibernate.HibernateException;
  5 import org.hibernate.SessionFactory;
  6 import org.hibernate.Transaction;
  7 import org.hibernate.cfg.Configuration;
  8 import org.hibernate.classic.Session;
  9 
 10 import com.Elastic.HibernateDemo2.ivy.entity.Dept;
 11 import com.Elastic.HibernateDemo2.ivy.entity.Emp;
 12 public class Test {
 13     public static void main(String[] args) {
 14         Configuration cfg = null;
 15         SessionFactory sessionFactory = null;
 16         Session session = null;
 17         Transaction tx = null;
 18         try {
 19             //1.读取配置文件
 20             cfg = new Configuration().configure();
 21             //2.创建会话工厂
 22             sessionFactory = cfg.buildSessionFactory();
 23             //3.通过会话工厂打开会话
 24             session = sessionFactory.openSession();
 25             //4.开启事务
 26             tx = session.beginTransaction();
 27             
 28             //5.业务
 29             /*  查询员工信息,以及员工所在部门   */
 30             /*Emp emp = (Emp) session.get(Emp.class, 1);
 31             System.out.println(emp.getEmpName());
 32             System.out.println(emp.getDeptId());
 33             
 34             System.out.println("员工表的信息");
 35             
 36             //如果使用这段代码,那么实体类Emp中的Dept对象就没用到
 37             Dept dept = (Dept) session.get(Dept.class, emp.getDeptId());
 38             System.out.println(dept.getDeptName());
 39             
 40             //Emp.hbm.xml配置文件中加了<many-to-one></many-to-one>
 41             System.out.println(emp.getDept().getDeptName());*/
 42             
 43             /* 查询某个部门,以及该部门下是所有的员工信息   */
 44             /*Dept dept = (Dept) session.get(Dept.class, 3);
 45             System.out.println("部门名称:" + dept.getDeptName());
 46             System.out.println("该部门的员工信息如下:" );
 47             Set<Emp> emps = dept.getEmps();
 48             System.out.println("个数:" + emps.size());
 49             for (Emp emp : emps) {
 50                 System.out.println(emp.getEmpName());
 51             }*/
 52             
 53             /* 新增部门的同时,新增员工   */
 54             /*Dept dept = new Dept();
 55             dept.setDeptName("开发部");
 56             dept.setLocation("6楼");
 57             
 58             Set<Emp> emps = new HashSet<Emp>();
 59             Emp emp = new Emp();
 60             emp.setEmpName("赵六");
 61             //id自增
 62             emp.setDept(dept);
 63             emps.add(emp);
 64             
 65             emp = new Emp();
 66             emp.setEmpName("黎明");
 67             emp.setDept(dept);
 68             emps.add(emp);
 69             
 70             //把所有的员工添加到部门中
 71             dept.setEmps(emps);
 72             
 73             session.save(dept);*/
 74             
 75             /* 删除部门 */
 76             /*Dept dept = (Dept) session.get(Dept.class, 5);
 77             
 78             //1.删除部门保留员工
 79             Dept dept1 = (Dept) session.get(Dept.class, 1);
 80             dept1.getEmps().addAll(dept.getEmps());
 81             
 82             //另一个部门接收
 83             session.update(dept1);
 84             
 85             //强制先执行update,再执行delete
 86             session.flush();
 87             session.delete(dept);*/
 88             
 89             //2.删除部门同时删除员工
 90             /*Dept dept = (Dept) session.get(Dept.class, 5);
 91             session.delete(dept);*/
 92             
 93             /* 类级别的懒加载。类级别不要管lazy,默认true */
 94             // load只查询主键(id)
 95             /*Dept dept = (Dept) session.load(Dept.class, 1);
 96             System.out.println(dept.getDeptId());
 97             System.out.println(dept.getDeptName());*/
 98             
 99             /*Dept dept = (Dept) session.get(Dept.class, 1);
100             System.out.println("查询了部门");
101             Set<Emp> emps = dept.getEmps();
102             System.out.println(emps.size());
103             for (Emp emp : emps) {
104                 System.out.println(emp.getEmpName());
105             }*/
106             
107             Emp emp = (Emp)session.get(Emp.class, 1);
108             System.out.println(emp.getEmpName());
109             System.out.println(emp.getDept().getDeptName());
110             
111             tx.commit();
112         } catch (HibernateException e) {
113             e.printStackTrace();
114             tx.rollback();
115         } finally {
116             if (null != session) {
117                 session.close();
118             }
119         }
120     }
121 }

       
可能遇到的问题:
    1.当Session关闭的时候页面延迟加载的数据不能读取
        解决方法:使用Open Session In View模式

===========================Session管理============================
Session不是线程安全,因此需要Session管理
=======================ThreadLocal====================
定义:
    不是线程的本地实现。即,它不是线程,而是线程局部变量
    
作用:
    每一个使用这个变量的线程都提供一个变量值的副本。每一个线程可独立改变自己的副本,不影响其他副本

注意:使用完毕后,手动改变Session

范例:

技巧:
    1.转发:/jsp★★★★★
    2.重定向:request.getContextPath()/★★★★★

范例:
1.实体类及其***.hbm.xml -- entity包
a.Dept

 1 package com.Elastic.HibernateDemo2.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     public Integer getDeptId() {
21         return deptId;
22     }
23     public void setDeptId(Integer deptId) {
24         this.deptId = deptId;
25     }
26     public String getDeptName() {
27         return deptName;
28     }
29     public void setDeptName(String deptName) {
30         this.deptName = deptName;
31     }
32     public String getLocation() {
33         return location;
34     }
35     public void setLocation(String location) {
36         this.location = location;
37     }
38 }


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.HibernateDemo2.ivy.entity.Dept" table="dept">
 9     
10         <!-- 主键OID(唯一标识) -->
11         <id name="deptId" column="deptid"><!-- column单独一行,属性更全 -->
12         
13             <!-- 主键生成策略:increment,assigned,native等 -->
14             <generator class="increment"></generator>
15         </id>
16         
17         <!-- 属性名(★★setDeptName★★):数据库表字段(如果是关键字,用``标志) -->
18         <property name="deptName" column="deptname"></property>
19         <property name="location" column="location"></property>
20         
21         <!-- 多个员工 -->
22         <!-- <set name="emps" cascade="save-update"> --><!-- 新增部门的同时,新增员工(级联操作) -->
23         <!-- <set name="emps" cascade="all" inverse="true" order-by="empNo desc"> --><!-- 删除部门同时删除员工 -->
24         <set name="emps" cascade="all" inverse="true" order-by="empNo desc" lazy="extra"><!-- 删除部门同时删除员工 -->
25             <!-- 表dept中deptid -->
26             <key column="deptid"></key>
27             <one-to-many class="com.Elastic.HibernateDemo2.ivy.entity.Emp"></one-to-many>
28         </set>
29         
30     </class>
31 </hibernate-mapping>


2.util包
a.HibernateUtil

 1 package com.Elastic.HibernateDemo2.ivy.util;
 2 import org.hibernate.Session;
 3 import org.hibernate.SessionFactory;
 4 import org.hibernate.cfg.Configuration;
 5 public class HibernateUtil {
 6     private static Configuration cfg = null;
 7     private static SessionFactory sessionFactory = null;
 8     
 9     static{
10         cfg = new Configuration().configure();
11         sessionFactory = cfg.buildSessionFactory();
12     }
13     
14     //本地线程
15     public static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
16     
17     
18     public static Session getSession(){
19         Session session = threadLocal.get();
20         if (null == session || !session.isOpen()) {
21             session = sessionFactory.openSession();
22             threadLocal.set(session);
23         }
24         return session;
25     }
26 }


3.filter包
a.OpenSessionInViewFilter

 1 package com.Elastic.HibernateDemo2.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.Session;
10 import org.hibernate.Transaction;
11 import com.Elastic.HibernateDemo2.ivy.util.HibernateUtil;
12 public class OpenSessionInViewFilter implements Filter{
13 
14     /* (non-Javadoc)
15      * @see javax.servlet.Filter#destroy()
16      */
17     @Override
18     public void destroy() {
19         // TODO Auto-generated method stub
20         
21     }
22 
23     /* (non-Javadoc)
24      * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
25      */
26     @Override
27     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
28             throws IOException, ServletException {
29         
30         //事务以及session的关闭
31         
32         Session session = HibernateUtil.getSession();
33         //开启事务
34         Transaction tx = session.beginTransaction();
35         try {
36             chain.doFilter(request, response);
37             //提交事务
38             tx.commit();
39         } catch (Exception e) {
40             e.printStackTrace();
41             tx.rollback();
42         } finally {
43             //关闭session
44             session.close();
45         }
46     }
47 
48     /* (non-Javadoc)
49      * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
50      */
51     @Override
52     public void init(FilterConfig arg0) throws ServletException {
53         // TODO Auto-generated method stub
54         
55     }
56 }


4.hibernate.cfg.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
 5 
 6 <hibernate-configuration>
 7     <session-factory>
 8         <!-- 1.连接数据库 -->
 9         <!-- 连接数据库名 -->
10         <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
11         
12         <!-- 连接数据库的用户名 -->
13         <property name="connection.username">root</property>
14         
15         <!-- 连接数据库的密码 -->
16         <property name="connection.password">root</property>
17         
18         <!-- 数据库驱动类 -->
19         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
20         
21         <!-- 2.数据库方言(不同的数据库) -->
22         <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
23         
24         <!-- 3.其他属性 -->
25         <!-- 是否显示sql语句 -->
26         <property name="show_sql">true</property>
27         <!-- 是否显示格式化sql语句,如果要显示,★★★一定要先显示show_sql语句★★★ -->
28         <property name="format_sql">true</property>
29         
30         <!-- 4.数据库对应的实体类的映射文件路径 -->
31         <mapping resource="com/Elastic/HibernateDemo2/ivy/entity/Dept.hbm.xml"></mapping>
32     </session-factory>
33 </hibernate-configuration>


5.dao包
a.DeptDao

 1 package com.Elastic.HibernateDemo2.ivy.dao;
 2 import java.io.Serializable;
 3 import java.util.List;
 4 import com.Elastic.HibernateDemo2.ivy.entity.Dept;
 5 public interface DeptDao {
 6     void save(Dept dept);
 7     
 8     void delete(Serializable id);
 9     
10     void update(Dept dept);
11     
12     Dept find(Serializable id);
13     
14     List<Dept> find();
15 }


6.dao.impl包
a.DeptDaoImpl

 1 package com.Elastic.HibernateDemo2.ivy.dao.impl;
 2 import java.io.Serializable;
 3 import java.util.List;
 4 import org.hibernate.Session;
 5 import com.Elastic.HibernateDemo2.ivy.dao.DeptDao;
 6 import com.Elastic.HibernateDemo2.ivy.entity.Dept;
 7 import com.Elastic.HibernateDemo2.ivy.util.HibernateUtil;
 8 public class DeptDaoImpl implements DeptDao {
 9 
10     /* (non-Javadoc)
11      * @see com.Elastic.HibernateDemo2.ivy.dao.DeptDao#save(com.Elastic.HibernateDemo2.ivy.entity.Dept)
12      */
13     @Override
14     public void save(Dept dept) {
15          HibernateUtil.getSession().save(dept);
16     }
17 
18     /* (non-Javadoc)
19      * @see com.Elastic.HibernateDemo2.ivy.dao.DeptDao#delete(java.io.Serializable)
20      */
21     @Override
22     public void delete(Serializable id) {
23         // TODO Auto-generated method stub
24 
25     }
26 
27     /* (non-Javadoc)
28      * @see com.Elastic.HibernateDemo2.ivy.dao.DeptDao#update(com.Elastic.HibernateDemo2.ivy.entity.Dept)
29      */
30     @Override
31     public void update(Dept dept) {
32         // TODO Auto-generated method stub
33 
34     }
35 
36     /* (non-Javadoc)
37      * @see com.Elastic.HibernateDemo2.ivy.dao.DeptDao#find(java.io.Serializable)
38      */
39     @Override
40     public Dept find(Serializable id) {
41         Session session = HibernateUtil.getSession();
42         System.out.println("DeptDaoImpl:" + session.hashCode());
43         return (Dept) session.get(Dept.class, id);
44     }
45 
46     /* (non-Javadoc)
47      * @see com.Elastic.HibernateDemo2.ivy.dao.DeptDao#find()
48      */
49     @Override
50     public List<Dept> find() {
51         // TODO Auto-generated method stub
52         return null;
53     }
54 }


7.service包
a.DeptService

1 package com.Elastic.HibernateDemo2.ivy.service;
2 import com.Elastic.HibernateDemo2.ivy.entity.Dept;
3 public interface DeptService {
4     Dept findDeptById(Integer id);
5 }


8.service.impl包
a.DeptServiceImpl

 1 package com.Elastic.HibernateDemo2.ivy.service.impl;
 2 import com.Elastic.HibernateDemo2.ivy.dao.DeptDao;
 3 import com.Elastic.HibernateDemo2.ivy.dao.impl.DeptDaoImpl;
 4 import com.Elastic.HibernateDemo2.ivy.entity.Dept;
 5 import com.Elastic.HibernateDemo2.ivy.service.DeptService;
 6 public class DeptServiceImpl implements DeptService {
 7     DeptDao deptDao = new DeptDaoImpl();
 8     
 9     /* (non-Javadoc)
10      * @see com.Elastic.HibernateDemo2.ivy.service.DeptService#findDeptById(java.lang.Integer)
11      */
12     @Override
13     public Dept findDeptById(Integer id) {
14         // TODO Auto-generated method stub
15         return deptDao.find(id);
16     }
17 }


9.servlet包
a.DeptServlet

 1 package com.Elastic.HibernateDemo2.ivy.controller;
 2 import java.io.IOException;
 3 import javax.servlet.ServletException;
 4 import javax.servlet.http.HttpServlet;
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 import com.Elastic.HibernateDemo2.ivy.service.DeptService;
 8 import com.Elastic.HibernateDemo2.ivy.service.impl.DeptServiceImpl;
 9 /**
10  * Servlet implementation class DeptServlet
11  */
12 public class DeptServlet extends HttpServlet {
13     private static final long serialVersionUID = 1L;
14        
15     /**
16      * @see HttpServlet#HttpServlet()
17      */
18     public DeptServlet() {
19         super();
20         // TODO Auto-generated constructor stub
21     }
22 
23     /**
24      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
25      */
26     protected void doGet(HttpServletRequest request, HttpServletResponse response)
27             throws ServletException, IOException {
28         
29         Integer deptId = Integer.parseInt(request.getParameter("deptId"));
30         DeptService deptService = new DeptServiceImpl();
31         request.setAttribute("dept", deptService.findDeptById(deptId));
32         //转发:/jsp★★★★★
33         request.getRequestDispatcher("/jsp/empTable.jsp").forward(request, response);
34     }
35 
36     /**
37      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
38      */
39     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
40         // TODO Auto-generated method stub
41         this.doGet(request, response);
42     }
43 }


10.jsp包
a.empTable.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 
 7 <table class="table table-bordered">
 8     <caption>${requestScope.dept.deptName }</caption>
 9     <thead>
10         <tr>
11             <td>员工编号</td>
12             <td>员工姓名</td>
13             <td>操作</td>
14         </tr>
15     </thead>
16     <tbody>
17         <c:forEach items="${requestScope.dept.emps }" var="emp">
18             <tr>
19                 <td>${emp.empNo }</td>
20                 <td>${emp.empName }</td>
21                 <td><a>删除</a></td>
22             </tr>
23         </c:forEach>
24     </tbody>
25 </table>


b.empList.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         <label>部门编号</label><input type="text" /><button>查询</button>
21         <div id="empTable">
22             <jsp:include page="empTable.jsp" flush="true"></jsp:include>
23         </div>
24     </div>
25     
26     <!-- 引用外部JS文件  -->
27     <!-- 重定向:request.getContextPath()/ ★★★★★-->
28     <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.11.3.min.js"></script><!-- ★★★★★注意路径★★★★★ -->
29     <script type="text/javascript" src="<%=request.getContextPath()%>/js/bootstrap.min.js"></script>
30 
31     <script type="text/javascript">
32         $(function() {
33             $('button').click(function() {
34                 <!-- 重定向:request.getContextPath()/ ★★★★★-->
35                 $('#empTable').load('<%=request.getContextPath()%>/emp/search?deptId=' + $(this).prev().val());
36             });
37             
38         });
39     
40     </script>
41 
42 </body>
43 </html>


   

原文地址:https://www.cnblogs.com/ivy-xu/p/5596787.html