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

 配置文件

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

 

转载于:https://www.cnblogs.com/hmy-1365/p/5773530.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值