Announcement Announcement Module
Collapse
No announcement yet.
No Session found for current thread. Spring Transactions. Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • No Session found for current thread. Spring Transactions.

    Hi.
    First of all thank you for such awesome framework like Spring.
    I got stucked with probably a newbie problem.
    I'm trying to integrate Hibernate 4.1.7 with Spring 3.1.2.
    I have a '@Transactional' method in my service and when it is invoked I've got an Exception:
    Code:
    org.hibernate.HibernateException: No Session found for current thread
    	at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
    	at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941)
    	at dao.UserConfigHomeImpl.findByName(UserConfigHomeImpl.java:124)
    	at facade.UserConfigFacade.findByName(UserConfigFacade.java:25)
    	at com.jsfsample.managedbeans.LoginBean.loadBuildings(LoginBean.java:85)
    	....
    Here are the classes where the exception occurs:
    Service( defined in applicationContext.xml ):
    Code:
    public class UserConfigFacade implements UserConfigFacadeService{
    
    	@Autowired UserConfigHomeImpl dao;
    	@Transactional(readOnly = true,propagation = Propagation.REQUIRED)
    	public UserConfig findByName(String nick)
    	{
                    UserConfig uc = dao.findByName(nick);
    		return uc;                                       
    	}
    it's interface:
    Code:
    public interface UserConfigFacadeService {
    
    	public UserConfig findByName(String nick);
    }
    my dao for UserConfig class:

    Code:
    public class UserConfigHomeImpl implements Dao{
    	
    	private SessionFactory sessionFactory;
    	public void setSessionFactory(SessionFactory sessionFactory)
    	{
    		this.sessionFactory = sessionFactory;
    	}
    	public void persist(UserConfig transientInstance) {
    		//log.debug("persisting UserConfig instance");
    		try {
    			sessionFactory.getCurrentSession().persist(transientInstance);
    			//log.debug("persist successful");
    		} catch (RuntimeException re) {
    			//log.error("persist failed", re);
    			throw re;
    		}
    	}
    
    	public void attachDirty(UserConfig instance) {
    		try {
    			sessionFactory.getCurrentSession().saveOrUpdate(instance);
    		} catch (RuntimeException re) {
    			throw re;
    		}
    	}
    
    	public void attachClean(UserConfig instance) {
    		try {
    			sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
    		} catch (RuntimeException re) {
    			throw re;
    		}
    	}
    
    	public void delete(UserConfig persistentInstance) {
    		try {
    			sessionFactory.getCurrentSession().delete(persistentInstance);
    		} catch (RuntimeException re) {
    			throw re;
    		}
    	}
    
    	public UserConfig merge(UserConfig detachedInstance) {
    		try {
    			UserConfig result = (UserConfig) sessionFactory.getCurrentSession()
    					.merge(detachedInstance);
    			return result;
    		} catch (RuntimeException re) {
    			throw re;
    		}
    	}
    
    	public UserConfig findById(java.lang.Integer id) {
    		try {
    			UserConfig instance = (UserConfig) sessionFactory
    					.getCurrentSession().get("pojo.UserConfig", id);
    			Hibernate.initialize(instance.getUsersCityConfigs());
    			return instance;
    		} catch (RuntimeException re) {
    			throw re;
    		}
    	}
    	@Transactional
    	public UserConfig findByName(String nick)
    	{
    		try {
    			Session session = sessionFactory.getCurrentSession();
    			Query q = session.createQuery(
    		                "Select uc from UserConfig uc " +
    		                "where uc.nick = :nick"
    		            );
                q.setParameter("nick", nick);
                Object obj  = (Object) q.uniqueResult();
                UserConfig uc = (UserConfig)obj;
                if(uc != null)
                Hibernate.initialize(uc.getUserRoles());    
    			return uc;
    		} catch (RuntimeException re) {
    			//log.error("get failed", re);
    			throw re;
    		}
    	}
    }
    it's interface:
    Code:
    public interface Dao {
    
    	UserConfig findByName(String nick);
    	void setSessionFactory(SessionFactory sessionFactory);
    	public void persist(UserConfig transientInstance);
    	public void attachDirty(UserConfig instance);
    	public void attachClean(UserConfig instance);
    	public void delete(UserConfig persistentInstance) ;
    	public UserConfig merge(UserConfig detachedInstance);
    	public UserConfig findById(java.lang.Integer id);
    }
    applicationContext.xml :
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:context="http://www.springframework.org/schema/context"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    	xmlns:faces="http://www.springframework.org/schema/faces"
    	xmlns:int-security="http://www.springframework.org/schema/integration/security"
    	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sec="http://www.springframework.org/schema/security"
    	xsi:schemaLocation="http://www.springframework.org/schema/integration/security http://www.springframework.org/schema/integration/security/spring-integration-security-2.0.xsd
    		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    		http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
    		http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
    		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    		http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-2.0.xsd
    		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:annotation-config/>
     <!--  mode="aspectj" -->
     <bean id="userConfigFacade" class="facade.UserConfigFacade"/>
    <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
    <context:component-scan base-package="com" >
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
    </context:component-scan>
    <context:component-scan base-package="facade" />
    <context:component-scan base-package="model" />
    <context:component-scan base-package="economy_computation" />
    <context:component-scan base-package="dao" />
    
    	
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost/ma" />
            <property name="username" value="root" />
            <property name="password" value="root" />
     </bean>
     
    <bean id="myUserConfigFacadeService" class="facade.UserConfigFacade">
     </bean>
      	
      <bean id="myUserConfigDao" class="dao.UserConfigHomeImpl">
      	<property name="sessionFactory" ref="sessionFactory"/>
      </bean>
      
      <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="mappingResources">
    	  <list>
    	    	<value>Capital.hbm.xml</value>
    	    	<value>CityLode.hbm.xml</value>
    	  </list>
    	  </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                    <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                    <prop key="hibernate.connection.pool_size">${hibernate.connection.pool_size}</prop>
                </props>
            </property>
     </bean>
    
     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
      		<property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
    	
    
    <sec:http auto-config="true" access-denied-page="/faces/accessDenied.xhtml">
    	<sec:form-login login-page="/faces/login.xhtml" />
    	<sec:intercept-url pattern="/faces/admin/**" access="ROLE_ADMIN" />	    
    </sec:http>
    
    	<!-- 
    	business logic (method) security 
    	-->
    
    <sec:global-method-security
    	secured-annotations="enabled" jsr250-annotations="enabled" >		
    </sec:global-method-security>
    	
    
    <bean id="daoAuthenticationProvider"
     class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
      <property name="userDetailsService" ref="userDetailsService"/>
    </bean>
    
    <bean id="authenticationManager"
        class="org.springframework.security.authentication.ProviderManager">
      <property name="providers">
        <list>
          <ref local="daoAuthenticationProvider" />
        </list>
      </property>
    </bean>
    
    <sec:authentication-manager>
      <sec:authentication-provider ref="daoAuthenticationProvider">
        <sec:password-encoder hash="md5"/>
      </sec:authentication-provider>
    </sec:authentication-manager>
    
    	
    </beans>
    Any suggestions ?

    Ohh, I forgot to say, that the UserConfigFacade Service is injected as Spring bean into jsf Session bean:
    Code:
    @ManagedBean(name = "loginBean")
    @SessionScoped
    public class LoginBean implements Serializable {
    	private static final long serialVersionUID = 1L;
    
    	private String login;
    	private String password;
    	private UserConfig uc = null;
    	private List<BuildingDTO> buildings;
    	@ManagedProperty(value = "#{modelDataProvider}")
    	private ModelFacade modelFacade;
    	@ManagedProperty(value = "#{userConfigFacade}")
    	private UserConfigFacade userConfigFacade;
    // methods
    }
    Last edited by friko16; Sep 28th, 2012, 02:59 PM.

  • #2
    Hello

    A lot of code

    I have many suggestions

    it is wrong

    Code:
    @Autowired XImpl myVar;
    Must be

    Code:
    @Autowired XService myVar;
    Declare the variable type working with interfaces because Spring work the Proxy Pattern to apply transactions.

    Use first @Transactional in a class level

    Code:
    @Transactional
    public class XImpl implements XService {
    
    
    }
    the methods within such class using again the @Transactional must override the values declared in the class level

    Your DAO classes must has the @Transactional too

    Code:
    @Transactional
    public class XDAOImpl implements XDAOService {
    
    
    }
    It is for let Spring has the DAO with the transactional control, remember DAO are called from BO/business object

    I think thats the reason of

    Code:
    org.hibernate.HibernateException: No Session found for current thread
    	at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
    Why the follow?

    Code:
    <context:component-scan base-package="facade" />
    <context:component-scan base-package="model" />
    <context:component-scan base-package="economy_computation" />
    <context:component-scan base-package="dao" />
    All them are in different packages?

    Since you are scanning why not use @Service and @Repository for Business and DAO classes respectively?

    Is not wise mix in a xml file DB configuration + Security configuration.

    Comment

    Working...
    X