-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: No Hibernate Session bound to thread...ERROR!! Please HELP!!
PostPosted: Thu Mar 03, 2011 12:13 am 
Newbie

Joined: Wed Feb 16, 2011 1:56 pm
Posts: 7
I'm trying to implement a login mechanism using Spring Security and Hibernate.

The settings work fine when I hardcode the login values in my DAO itself and run the application. But when I try to use Hibernate it throws the following error:

Code:
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here


My spring-security.xml file
Code:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:security="http://www.springframework.org/schema/security"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/security
         http://www.springframework.org/schema/security/spring-security-3.0.xsd">
   
   <!-- This is where we configure Spring-Security  -->
   <security:http auto-config="true" use-expressions="true" access-denied-page="/auth/denied" >
   
      <security:intercept-url pattern="/auth/login" access="permitAll"/>
      <security:intercept-url pattern="/main/admin" access="hasRole('ROLE_ADMIN')"/>
      <security:intercept-url pattern="/main/common" access="hasRole('ROLE_USER')"/>
      
      <security:form-login
            login-page="/auth/login"
            authentication-failure-url="/auth/login?error=true"
            default-target-url="/main/common"/>
         
      <security:logout
            invalidate-session="true"
            logout-success-url="/auth/login"
            logout-url="/auth/logout"/>
   
   </security:http>
   
   <!-- Declare an authentication-manager to use a custom userDetailsService -->
   <security:authentication-manager>
           <security:authentication-provider user-service-ref="loginService">
                 <security:password-encoder ref="passwordEncoder"/>
           </security:authentication-provider>
   </security:authentication-manager>
   
   <!-- Use a Md5 encoder since the user's passwords are stored as Md5 in the database -->
   <bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder"/>

   <!-- A custom service where Spring will retrieve users and their corresponding access levels  -->
   <bean id="loginService" class="com.myaudition.contact.service.LoginService"/>
   
</beans>


In my spring-servlet.xml I've the transaction manager defined(which works fine for the rest of the application)
Code:
<bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>


The login service class:
Code:
@Service
public class LoginService implements UserDetailsService {
   
   @Autowired
   private UserDAO userDAO;

   @Transactional
   public UserDetails loadUserByUsername(String username)
         throws UsernameNotFoundException, DataAccessException {

      UserDetails user = null;
      
      try {
         Login dbUser = userDAO.searchDatabase(username);
         
         user =  new User(
               dbUser.getEmail(),
               dbUser.getPassword().toLowerCase(),
               true,
               true,
               true,
               true,
               getAuthorities(dbUser.getIdentifierId()) );

      } catch (Exception e) {
         throw new UsernameNotFoundException("Error in retrieving user");
      }
      
      return user;
   }


The UserDAO class:
Code:
@Repository
public class UserDAO {

   @Autowired
    private SessionFactory sessionFactory;
   
   /**
    * Simulates retrieval of data from a database.
    */
   @SuppressWarnings("unchecked")
   public Login searchDatabase(String username) {
      // Retrieve all users from the database
      List<Login> users = new ArrayList<Login>();

      Session session = sessionFactory.getCurrentSession();

      Query query = session.createQuery(" from Login");
      users = query.list();

      // Search user based on the parameters
      for(Login dbUser:users) {
         if ( dbUser.getEmail().equals(username)  == true ) {
            // return matching user
            return dbUser;
         }
      }
      throw new RuntimeException("User does not exist!");
   }
}


In the above code, the code breaks while trying to get the current session & gives the following error:

Code:
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here


Please guide me. How do i attach a hibernate session with this thread? What am i doing wrong?


Top
 Profile  
 
 Post subject: Re: No Hibernate Session bound to thread...ERROR!! Please HELP!!
PostPosted: Wed Jun 01, 2011 9:31 am 
Newbie

Joined: Wed Jun 01, 2011 9:26 am
Posts: 1
I'm having the same problem. Can someone bring some light?

The configuration seems to be ok:

-transactionManager is declared and tx:annotation-driven annotated
-A service method annotated with @Transactional calls a DAO method that tryes to get the session: sessionFactory.getCurrentSession()


Top
 Profile  
 
 Post subject: Re: No Hibernate Session bound to thread...ERROR!! Please HELP!!
PostPosted: Fri Jul 29, 2011 8:17 am 
Newbie

Joined: Fri Jul 29, 2011 8:09 am
Posts: 1
Instead of
Session session = sessionFactory.getCurrentSession();

Try
Session session = sessionFactory.getOpenSession();

Or make following entry in web.xml

<filter>
<filter-name>HibernateSession</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>HibernateSession</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

The reason behind this issue is hibernate session is not bound with HTTP request by deafult. You have to bind it. So whether you open it directly or use spring provided interceptor.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.