【转】Spring与Hibernate集成中的session问题(getSession()、getCurrentSession()与openSession() )

主要讨论Spring与Hibernate集成中的session问题

1.通过getSession()方法获得session进行操作

Java代码   收藏代码
  1. public class Test  extends HibernateDaoSupport{  
  2.      public void save(User user){  
  3.         this.getSession().save(user);  
  4.      }  
  5. }    

利用这种方式获得的session在方法执行结束之后不会自动关闭连接,也就是说我们必须通过session.close()或者releaseSession(session)来手动进行关闭,否则会造成内存泄露或者连接耗尽等问题。手动关闭:
Java代码   收藏代码
  1. public class Test  extends HibernateDaoSupport{  
  2.      public void save(User user){  
  3.         Session session = this.getSession();  
  4.         session.save(user);  
  5.         session.close();  
  6.         // releaseSession(session);   
  7.      }  
  8. }   

如果对上述方法进行事务控制,那么spring框架会自动为我们关闭session,此种情况下再执行上述代码,会抛出如下异常:
Java代码   收藏代码
  1.  org.springframework.orm.hibernate3.HibernateSystemException: Session is closed; nested exception is org.hibernate.SessionException: Session is closed  
  2. …  
  3. org.hibernate.SessionException: Session is closed  

提示session已经关闭。但是如果在代码中通过releaseSession(session)的方法来关闭session,则不会抛出异常。releaseSession(session)方法的代码如下:
Java代码   收藏代码
  1. protected final void releaseSession(Session session) {  
  2.     SessionFactoryUtils.releaseSession(session, getSessionFactory());  
  3. }  

也就是说它是通过SessionFactoryUtils的releaseSession方法来实现的:
Java代码   收藏代码
  1. public static void releaseSession(   
  2.      Session session,SessionFactory sessionFactory) {  
  3.           if (session == null) {  
  4.               return;  
  5.           }  
  6.           // Only close non-transactional Sessions.  
  7.           if (!isSessionTransactional(session,sessionFactory))   {  
  8.              closeSessionOrRegisterDeferredClose  (session, sessionFactory);  
  9.           }  
  10.     }  

可见它内部会先进行判断。

查看getSession()方法的源码:

Java代码   收藏代码
  1. protected final Session getSession()  
  2.         throws DataAccessResourceFailureException, IllegalStateException {  
  3.   
  4.         return getSession(this.hibernateTemplate.isAllowCreate());  
  5. }  

getSession()方法内部通过它的一个重载方法getSession(boolean allowCreate )来实现,变量allowCreate是HibernateTemplate中的变量,默认值为true,也就是创建一个新的session。如果我们调用getSession(false)来获得session,那么必须对其进行事务控制,原因是:(spring文档)
Java代码   收藏代码
  1. protected  final  org.hibernate.Session  getSession()   
  2. throws DataAccessResourceFailureException,   IllegalStateException    
  3.   
  4. Get a Hibernate Session, either from the current transaction or a new one. The latter is only allowed if the "allowCreate" setting of this bean's HibernateTemplate is true.   

也就是说,getSession()方法从当前事务或者一个新的事务中获得session,如果想从一个新的事务中获得session(也就意味着当其不存在事务控制),则必须使HibernateTemplate中的allowCreate变量的值为”true”,而现在设置allowCreate变量的值为”false”就意味着无法从新的事务中获得session,也就是只能从当前事务中获取,所以必须对当前方法进行事务控制,否则会抛出如下异常:
Java代码   收藏代码
  1. java.lang.IllegalStateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here ...  

同时,如果对getSession()所在的方法进行事务控制,那么类似如下的代码:
Java代码   收藏代码
  1. Session session = null;  
  2. for(int m =0;m<5;m++){  
  3.     Admin admin = new Admin();  
  4.     admin.setName("test");  
  5.     admin.setPassword("098");     
  6.     session = this.getSession();  
  7.     session.save(admin);  
  8. }  

只会打开一个session,因为事务控制必须确保是同一个连接,spring会确保在整个相关方法中只存在一个session。Spring在方法开始时会打开一个session(即使进行事务控制的方法内部不执行数据库操作),之后在请求session时,如果在事务中存在一个未commit的session就返回,以此确保同一个session。

2.getCurrentSession()与openSession()
getCurrentSession()与openSession()方法通过Hibernate的SessionFactory获得,两者的区别网上有很多文章已经介绍过,即:
Java代码   收藏代码
  1. ①getCurrentSession创建的session会和绑定到当前线程,而openSession不会。   
  2. ②getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭  


对于getCurrentSession()方法:
        (1)其所在方法必须进行事务控制
        (2)Session在第一次被使用的时候,或者第一次调用getCurrentSession()的时候,其生命周期就开始。然后它被Hibernate绑定到当前线程。当事务结束的时候,不管是提交还是回滚,Hibernate也会把Session从当前线程剥离,并且关闭它。假若你再次调用getCurrentSession(),你会得到一个新的Session,并且开始一个新的工作单元。    
  
对于openSession()方法:
         这个方法一般在spring与Hibernate的集成中不直接使用,它就是打开一个session,并且这个session与上下文无关,如果对其所在方法进行事务控制,会发现不起作用,原因就是前面提到的,事务控制必须确保是同一个连接,而openSession()打开的session与上下文无关。这个方法与getSession(),getCurrentSession()以及getHibernateTemplate()等方法的区别在于:后面的几个方法spring可以对其进行控制,如果对它们所在的方法进行事务控制,spring可以确保是同一个连接,而openSession()方法,spring无法对其进行控制,所以事务也不会起作用。


3.OpenSessionInView
OpenSessionInView的主要功能是用来把一个Hibernate Session和一次完整的请求过程对应的线程相绑定。Open Session In View在request把session绑定到当前thread期间一直保持hibernate session在open状态,使session在request的整个期间都可以使用,如在View层里PO也可以lazy loading数据,如 ${ company.employees }。当View 层逻辑完成后,才会通过Filter的doFilter方法或Interceptor的postHandle方法自动关闭session。
Java代码   收藏代码
  1. public class Group implements Serializable{   
  2.     private int id;   
  3.     private String name;   
  4.     private Set users;  
  5.          ...  
  6. }  

在业务方法中加载Group对象并将其保存到HttpSession对象中
Java代码   收藏代码
  1. List groups = ht.find("from Group");  
  2. Group group = (Group)groups.get(0);  
  3. HttpSession session = ServletActionContext.getRequest().getSession();  
  4. session.setAttribute("group", group);  

注意Group采用默认的延迟加载机制,即此时返回的只是一个Group代理对象,
在jsp页面中显示group对象的users属性,如下:

Java代码   收藏代码
  1. <%    
  2.      Group group = (Group)session.getAttribute("group");  
  3.      out.println(group.getUsers());  
  4. %>   

此时会抛出如下异常:
Java代码   收藏代码
  1. org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: entity.Group.users, no session or session was closed  

延迟加载机制使得在业务方法执行结束之后仅仅返回Group的一个代理对象,在jsp页面中使用到group对象的值时,才发出sql语句加载,但此时session已经关闭。解决方法是采用OpenSessionInView机制,在web.xml页面中配置如下过滤器:
Java代码   收藏代码
  1. <filter>    
  2.    <filter-name>hibernateFilter</filter-name>   
  3.    <filter-class>   
  4. org.springframework.orm.hibernate3.support.OpenSessionInViewFilter  
  5.    </filter-class>    
  6. </filter>  


总结:
(1)对于getSession(),getSession(false),getCurrentSession()以及getHibernateTemplate()方法而言,如果对其所在方法进行事务控制,那么可以确保在整个方法中只存在一个session,无论你执行了几次CRUD操作,并且所打开的session会在事务结束时自动关闭。
(2) 必须对getSession(false)以及getCurrentSession()所在的方法进行事务控制(原因见上述分析)
(3)如果没有对getSession()以及getHibernateTemplate()所在方法进行事务控制,那么如果在方法中进行N次CRUD操作,就会打开N个session,即每次调用getSession()和getHibernateTemplate()方法都会打开新的session。这两个方法的区别在于:getHibernateTemplate()方法结束时会自动关闭连接,而getSession()方法必须手动关闭。
(4) 如果在方法中采用SessionFactory的openSession()方法获得连接进行操作,那么无法对其进行事务控制。
(5) 一般的开发中,通常采用getHibernateTemplate()方法进行数据库操作, getHibernateTemplate()方法采用模板+回调的机制,进行数据库操作很方便,可以查看(其中session的打开与关闭都是在doExecute方法中进行的):

http://lijiejava.iteye.com/blog/667644

http://lijiejava.iteye.com/blog/727249


转自: http://www.iteye.com/topic/733971

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的Spring Boot cookie与session登陆界面的代码示例。 首先是UserController.java: ``` @Controller public class UserController { @Autowired private UserService userService; @GetMapping("/") public String index(Model model) { return "index"; } @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password, HttpServletResponse response, HttpServletRequest request) { User user = userService.getUser(username, password); if(user != null) { HttpSession session = request.getSession(true); session.setAttribute("user", user.getUsername()); Cookie cookie = new Cookie("user", user.getUsername()); cookie.setMaxAge(60*60*24); response.addCookie(cookie); return "redirect:/dashboard"; } else { return "index"; } } @GetMapping("/dashboard") public String dashboard(Model model, HttpServletRequest request) { HttpSession session = request.getSession(false); if(session == null) { return "index"; } else { String username = (String) session.getAttribute("user"); if(username == null) { return "index"; } else { model.addAttribute("username", username); return "dashboard"; } } } @GetMapping("/logout") public String logout(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(false); if(session != null) { session.removeAttribute("user"); session.invalidate(); } Cookie cookie = new Cookie("user", null); cookie.setMaxAge(0); response.addCookie(cookie); return "index"; } } ``` 这个类处理了登陆、认证和登出逻辑,使用了HttpSession和Cookie来存储用户状态。具体而言,当用户登陆时,UserController会调用UserService来验证用户名和密码,如果验证通过,UserController会创建一个新的HttpSession并将用户信息存储在其,同时会创建一个新的Cookie来存储用户信息,并将Cookie添加到HttpServletResponse。当用户访问dashboard页面时,UserController会先检查是否存在有效的HttpSession,如果存在,则从获取用户信息并将其传递给Model。当用户登出时,UserController会将HttpSession和Cookie失效,并将用户重定向到登陆页面。 接下来是UserService.java: ``` @Service public class UserService { private static final List<User> users = Arrays.asList( new User("admin", "admin"), new User("user", "password"), new User("test", "test") ); public User getUser(String username, String password) { for(User user : users) { if(user.getUsername().equals(username) && user.getPassword().equals(password)) { return user; } } return null; } } ``` 这个类模拟了一个简单的用户管理系统,只有三个用户(admin,user和test),每个用户都有一个用户名和密码。UserService类提供了一个getUser方法,用于验证用户名和密码是否正确。实际情况下,这个方法会调用数据库或者其它身份认证服务来获取正确的用户信息。 最后是View层: index.html ``` <!DOCTYPE html> <html> <head> <title>Spring Boot Cookie and Session Login Example</title> </head> <body> <h1>Spring Boot Cookie and Session Login Example</h1> <form method="post" action="/login"> <label>Username:</label> <input type="text" name="username"></input> <br/> <label>Password:</label> <input type="password" name="password"></input> <br/> <input type="submit" value="Login"></input> </form> </body> </html> ``` dashboard.html: ``` <!DOCTYPE html> <html> <head> <title>Dashboard - Spring Boot Cookie and Session Login Example</title> </head> <body> <h1>Welcome, ${username}!</h1> <a href="/logout">Logout</a> </body> </html> ``` 这个例子的View层非常简单,只包含了一个登陆表单和一个dashboard页面。当用户成功登陆后,会重定向到dashboard页面并显示用户信息。当用户登出时,会返回到登陆页面。 注意:以上代码是一个简单的示例,实际使用时还需要加入错误处理、安全认证等功能来提高系统的鲁棒性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值