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

 

 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

 

 1 package cn.happy.ui;
 2 
 3 import org.hibernate.Session;
 4 import org.hibernate.SessionFactory;
 5 import org.hibernate.Transaction;
 6 import org.hibernate.cfg.Configuration;
 7 
 8 import cn.happy.biz.UsersBiz;
 9 import cn.happy.entity.Users;
10 import cn.happy.until.HibernateUtil;
11 
12 public class Test {
13   public static void main(String[] args) {
14       get();
15 }
16   //添加
17   public static void add(){
18       Users user=new Users();
19       user.setName("回青");
20       user.setIsAdmin("yes");
21       user.setPassword("123456");
22       user.setTelephone("18265808945");
23       user.setUserName("戶夢艷");
24       UsersBiz usersBiz=new UsersBiz();
25       usersBiz.save(user);
26       System.out.println("ok");
27       
28   }
29  //修改
30   public static void modify(){
31       Session session = HibernateUtil.currentSession();
32       Transaction transaction = session.beginTransaction();
33       Users user = (Users)session.get(Users.class, 6);
34       user.setName("歲月靜好");
35       session.update(user);
36       transaction.commit();
37       HibernateUtil.closeSession();
38   }
39   
40   //
41   public static void get(){
42       UsersBiz ub=new UsersBiz();
43       Users user = (Users)ub.get(Users.class, 6);
44       System.out.println(user.getName());
45   }
46 }
測試類

 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

 配置文件

從網址訪問即可達到過濾器的作用

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM