Hibernate中多种方式解除延迟加载

 

 

问题引发:因为dao使用load(),默认延迟加载的,当在biz关闭session之后,UI层无法获取对象的非id属性值

解决方案:

1.变成get,即时加载

2.用Hibernate.isInitialized(obj)被初始化

3.类级别的lazy属性设为true

4.用final修饰类,因为用final修饰的类不允许有子类。而我们所说的内存中保存的代理对象其实就是该类的子类。此方法从根本上解决了延迟加载

5.在事务提交之前,先调用一下该类的非id属性

 1 package cn.happy.entity;
 2 
 3 public class Users {
 4     private Integer id;
 5     private String name;
 6     private String password;
 7     private String telephone;
 8     private String userName;
 9     private String isAdmin;
10     
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name;
26     }
27 
28     public String getPassword() {
29         return password;
30     }
31 
32     public void setPassword(String password) {
33         this.password = password;
34     }
35 
36     public String getTelephone() {
37         return telephone;
38     }
39 
40     public void setTelephone(String telephone) {
41         this.telephone = telephone;
42     }
43 
44     public String getUserName() {
45         return userName;
46     }
47 
48     public void setUserName(String userName) {
49         this.userName = userName;
50     }
51 
52     public String getIsAdmin() {
53         return isAdmin;
54     }
55 
56     public void setIsAdmin(String isAdmin) {
57         this.isAdmin = isAdmin;
58     }
59 
60 }
User.java
 1 <?xml version="1.0"?>
 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 
 7     <hibernate-mapping package="cn.happy.entity">
 8 
 9         <class name="Users" table="USERS" lazy="false">
10             <id name="id" column="ID">
11                 <generator class="native" />
12             </id>
13             <property name="name" type="string" column="NAME" />
14             <property name="password" />
15             <property name="telephone" />
16             <property name="userName" />
17             <property name="isAdmin" />
18         </class>
19 
20 </hibernate-mapping>
Users.hbm.xml

 

 

 1 package cn.happy.dao;
 2 
 3 import java.io.Serializable;
 4 
 5 import cn.happy.until.HibernateUtil;
 6 
 7 public class UsersDao {
 8    //添加用户记录
 9     public Serializable save(Object object){
10         return HibernateUtil.currentSession().save(object);
11     } 
12     //检索oid
13     public Object get(Class clazz, Serializable id){
14         return HibernateUtil.currentSession().load(clazz, id);
15     }
16     
17     //修改用户记录
18     public void update(Object object){
19         HibernateUtil.currentSession().update(object);
20     }
21     
22 }
UsersDao

 

 package cn.happy.ui;
 
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.hibernate.cfg.Configuration;
 
 import cn.happy.biz.UsersBiz;
 import cn.happy.entity.Users;
 import cn.happy.until.HibernateUtil;
 
 public class Test {
   public static void main(String[] args) {
       get();
 }
   //添加
   public static void add(){
       Users user=new Users();
       user.setName("name");
       user.setIsAdmin("yes");
       user.setPassword("123456");
       user.setTelephone("18265808945");
       user.setUserName("username");
       UsersBiz usersBiz=new UsersBiz();
       usersBiz.save(user);
       System.out.println("ok");
       
   }
  //修改
   public static void modify(){
       Session session = HibernateUtil.currentSession();
       Transaction transaction = session.beginTransaction();
       Users user = (Users)session.get(Users.class, 6);
       user.setName("name1");
       session.update(user);
       transaction.commit();
       HibernateUtil.closeSession();
   }
   
   //
   public static void get(){
       UsersBiz ub=new UsersBiz();
       Users user = (Users)ub.get(Users.class, 6);
       System.out.println(user.getName());
   }
 }

 

 1 package cn.happy.biz;
 2 
 3 import java.io.Serializable;
 4 
 5 import org.hibernate.Hibernate;
 6 import org.hibernate.Transaction;
 7 
 8 import cn.happy.dao.UsersDao;
 9 import cn.happy.until.HibernateUtil;
10 
11 public class UsersBiz {
12     UsersDao user=new UsersDao();
13     //添加用户记录
14     public Serializable save(Object object){
15         Transaction tx=HibernateUtil.currentSession().beginTransaction();
16         Serializable result=user.save(object);
17         tx.commit();
18         return result;
19     } 
20     //检索oid
21     public Object get(Class clazz, Serializable id){
22         Transaction tx = HibernateUtil.currentSession().beginTransaction();
23         Object obj=user.get(clazz, id);
24 //        if(!Hibernate.isInitialized(obj)){
25 //            Hibernate.initialize(obj);
26 //        }
27         tx.commit();
28         HibernateUtil.closeSession();
29         return obj;
30     }
31     
32     //修改用户记录
33     public void update(Object object){
34         Transaction tx=HibernateUtil.currentSession().beginTransaction();
35         user.update(object);
36         tx.commit();
37     }
38 }
UsersBiz

 

 package cn.happy.ui;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.hibernate.cfg.Configuration; 
 import cn.happy.biz.UsersBiz;
 import cn.happy.entity.Users;
 import cn.happy.until.HibernateUtil;
 
 public class Test {
   public static void main(String[] args) {
       get();
 }
   //添加
   public static void add(){
       Users user=new Users();
       user.setName("name");
       user.setIsAdmin("yes");
       user.setPassword("123456");
       user.setTelephone("18265808945");
       user.setUserName("username");
       UsersBiz usersBiz=new UsersBiz();
       usersBiz.save(user);
       System.out.println("ok");
       
   }
  //修改
   public static void modify(){
       Session session = HibernateUtil.currentSession();
       Transaction transaction = session.beginTransaction();
       Users user = (Users)session.get(Users.class, 6);
       user.setName("name1");
       session.update(user);
       transaction.commit();
       HibernateUtil.closeSession();
   }
   
   //
   public static void get(){
       UsersBiz ub=new UsersBiz();
       Users user = (Users)ub.get(Users.class, 6);
       System.out.println(user.getName());
   }
 }
测试类

 

 6.用openSessionInView模式

Open Session In View模式的主要思想:在用户的每一次请求过程始终保持 一个Session对象打开着

 

过滤器:过滤用的。过滤请求和响应。双向过滤

实现步骤:

 

Until包

 1 package cn.happy.until;
 2 
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.cfg.Configuration;
 6 
 7 public class HibernateUtil {
 8      private static final ThreadLocal sessionTL=new ThreadLocal();
 9      private static Configuration configuration;
10      private final static SessionFactory sessionFactory;
11      static{
12         configuration=new Configuration().configure();
13         sessionFactory=configuration.buildSessionFactory(); 
14      }
15      public static Session currentSession(){
16             Session session=(Session)sessionTL.get();
17             //如果session为null,则打开一个新的session
18             if(session==null){
19                 session=sessionFactory.openSession();
20                 sessionTL.set(session);
21             }
22             return session;
23         }
24      public static void closeSession(){
25          Session session=(Session)sessionTL.get();
26          sessionTL.set(null);
27          session.close();
28      }
29 }
 1 package cn.happy.entity;
 2 
 3 public class Users {
 4     private Integer id;
 5     private String name;
 6     private String password;
 7     private String telephone;
 8     private String userName;
 9     private String isAdmin;
10     
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name;
26     }
27 
28     public String getPassword() {
29         return password;
30     }
31 
32     public void setPassword(String password) {
33         this.password = password;
34     }
35 
36     public String getTelephone() {
37         return telephone;
38     }
39 
40     public void setTelephone(String telephone) {
41         this.telephone = telephone;
42     }
43 
44     public String getUserName() {
45         return userName;
46     }
47 
48     public void setUserName(String userName) {
49         this.userName = userName;
50     }
51 
52     public String getIsAdmin() {
53         return isAdmin;
54     }
55 
56     public void setIsAdmin(String isAdmin) {
57         this.isAdmin = isAdmin;
58     }
59 
60 }
HibernateUtil.javaUser.java

entity包

 1 package cn.happy.entity;
 2 
 3 public class Users {
 4     private Integer id;
 5     private String name;
 6     private String password;
 7     private String telephone;
 8     private String userName;
 9     private String isAdmin;
10     
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name;
26     }
27 
28     public String getPassword() {
29         return password;
30     }
31 
32     public void setPassword(String password) {
33         this.password = password;
34     }
35 
36     public String getTelephone() {
37         return telephone;
38     }
39 
40     public void setTelephone(String telephone) {
41         this.telephone = telephone;
42     }
43 
44     public String getUserName() {
45         return userName;
46     }
47 
48     public void setUserName(String userName) {
49         this.userName = userName;
50     }
51 
52     public String getIsAdmin() {
53         return isAdmin;
54     }
55 
56     public void setIsAdmin(String isAdmin) {
57         this.isAdmin = isAdmin;
58     }
59 
60 }
Users.java
 1 <?xml version="1.0"?>
 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 
 7     <hibernate-mapping package="cn.happy.entity">
 8 
 9         <class name="Users" table="USERS">
10             <id name="id" column="ID">
11                 <generator class="native" />
12             </id>
13             <property name="name" type="string" column="NAME" />
14             <property name="password" />
15             <property name="telephone" />
16             <property name="userName" />
17             <property name="isAdmin" />
18         </class>
19 
20 </hibernate-mapping>
Users.hbm.xml

Dao包

 1 package cn.happy.dao;
 2 
 3 import java.io.Serializable;
 4 
 5 import cn.happy.until.HibernateUtil;
 6 
 7 public class UsersDao {
 8    //添加用户记录
 9     public Serializable save(Object object){
10         return HibernateUtil.currentSession().save(object);
11     } 
12     //检索oid
13     public Object get(Class clazz, Serializable id){
14         return HibernateUtil.currentSession().load(clazz, id);
15     }
16     
17     //修改用户记录
18     public void update(Object object){
19         HibernateUtil.currentSession().update(object);
20     }
21     
22 }
UsersDao.java

Biz包

 1 package cn.happy.biz;
 2 
 3 import java.io.Serializable;
 4 
 5 import org.hibernate.Hibernate;
 6 import org.hibernate.Transaction;
 7 
 8 import cn.happy.dao.UsersDao;
 9 import cn.happy.until.HibernateUtil;
10 
11 public class UsersBiz {
12     UsersDao user=new UsersDao();
13     //添加用户记录
14     public Serializable save(Object object){
15         Transaction tx=HibernateUtil.currentSession().beginTransaction();
16         Serializable result=user.save(object);
17         tx.commit();
18         return result;
19     } 
20     //检索oid
21     public Object get(Class clazz, Serializable id){
22         //Transaction tx = HibernateUtil.currentSession().beginTransaction();
23         Object obj=user.get(clazz, id);
24 //        if(!Hibernate.isInitialized(obj)){
25 //            Hibernate.initialize(obj);
26 //        }
27         //tx.commit();
28         //HibernateUtil.closeSession();
29         return obj;
30     }
31     
32     //修改用户记录
33     public void update(Object object){
34         Transaction tx=HibernateUtil.currentSession().beginTransaction();
35         user.update(object);
36         tx.commit();
37     }
38 }
UsersBiz.java

Filter包

 1 package cn.happy.filter;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 
12 import org.hibernate.HibernateException;
13 import org.hibernate.Session;
14 import org.hibernate.Transaction;
15 
16 import cn.happy.until.HibernateUtil;
17 
18 public class OpenSessionInViewFilter implements Filter {
19 
20     
21     public void doFilter(ServletRequest request, ServletResponse response,
22             FilterChain chain) throws IOException, ServletException {
23         request.setCharacterEncoding("utf-8");
24         Session session=null;
25         Transaction tx=null;
26         try {
27             session=HibernateUtil.currentSession();
28             System.out.println("filter\t"+session.hashCode());
29             tx=session.beginTransaction();
30             //执行请求处理链   双向过滤
31             chain.doFilter(request, response);
32             //返回响应  提交事务
33             tx.commit();
34         } catch (HibernateException e) {
35             e.printStackTrace();
36             tx.rollback();
37         }finally{
38             HibernateUtil.closeSession();
39         }
40         
41     }
42 
43     public void init(FilterConfig arg0) throws ServletException {
44         // TODO Auto-generated method stub
45         
46     }
47     public void destroy() {
48         // TODO Auto-generated method stub
49         
50     }
51 
52 
53 }
OpensessionInviewFilter

 配置文件

从网址访问即可达到过滤器的作用

 

posted @ 2016-08-15 16:48  回青  阅读(2503)  评论(1编辑  收藏  举报