Announcement Announcement Module
Collapse
No announcement yet.
Session is closed!( Integration of Spring+Jpa/Hibernate) Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Session is closed!( Integration of Spring+Jpa/Hibernate)

    Hello every One !
    When I am using EntityManager for getting a session I was getting org.hibernate.SessionException: Session is closed!

    Here is the Code for that Please help me in solving this!

    persistence.xml

    Code:
    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
        http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    	version="1.0">
    	<persistence-unit name="dbschema">
    		<properties>
    			<property name="hibernate.ejb.cfgfile" value="/hibernate.cfg.xml" />
    		</properties>
    	</persistence-unit>
    </persistence>
    hibernate.cfg.xml

    Code:
    <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
    	<session-factory>
    	</session-factory>
    </hibernate-configuration>
    app-config.xml

    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:context="http://www.springframework.org/schema/context"
    	xmlns:tx="http://www.springframework.org/schema/tx" 
    	xmlns:p="http://www.springframework.org/schema/p"
    	xmlns:task="http://www.springframework.org/schema/task"
    	xmlns:cache="http://www.springframework.org/schema/cache"
    	xsi:schemaLocation="
    		http://www.springframework.org/schema/beans	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd
    		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
    		
        	<context:annotation-config/>
        		
    		<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
    		<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
    		
    		<!--
    		scans the classpath of this application for @Components to deploy as
    		beans
    		-->
    		<context:component-scan base-package="com.cdis.flod.web"/>
    		<context:component-scan base-package="com.cdis.flod.dao"/>
    		<context:component-scan base-package="com.cdis.flod.service"/>
    		<context:component-scan base-package="com.cdis.flod.common"/>
    		
    		<!-- Schedule -->
        <task:annotation-driven/>
    		
    		<!-- Configures Spring MVC -->
    		<import resource="mvc-config.xml" />
    		
    		<!--
    		Configurer that replaces ${...} place holders with values from a
    		properties file (in this case, JDBC-related settings for the
    		dataSource definition below).
    		-->
    		<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	        <property name="locations">
    	            <list>
    	                <value>classpath*:*.properties</value>
    	                <!-- <value>classpath:localhost.properties</value> -->
    	            </list>
    	        </property>
    	       <property name="ignoreUnresolvablePlaceholders" value="true"/>
    		</bean>
    
    
    		
    		<!--
    		Uses Apache Commons DBCP for connection pooling. See Commons DBCP
    		documentation for the required JAR files. Alternatively you can use
    		another connection pool such as C3P0, similarly configured using
    		Spring.
    	-->
    		
    		<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    		destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
    		p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}"
    		p:initialSize="${dbcp.initialSize}" p:maxActive="${dbcp.maxActive}"
    		p:maxIdle="${dbcp.maxIdle}" p:maxWait="${dbcp.maxWait}"
    		p:defaultAutoCommit="${dbcp.defaultAutoCommit}" />
    		<!-- 
    		 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    			<property name="dataSource" ref="dataSource">
    			</property> 
    			<property name="hibernateProperties"> 
    				<props>
    					<prop key="hibernate.dialect">${hibernate.dialect}</prop>
    					<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
    				</props>
    			</property> 
    		</bean>  -->
    		
    		<!-- Spring-enabled container-managed JPA without any EJB container -->
    	<bean id="entityManagerFactory"	class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    		<property name="dataSource" ref="dataSource" />
    		<property name="persistenceUnitName" value="dbschema" />
    		<property name="jpaVendorAdapter">
    			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    				<property name="showSql" value="${jpa.showSql}" />
    			</bean>
    		</property>
    		<property name="jpaProperties">
    			<props>
    				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
    				<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
    				<!-- 
    				<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</prop>
    				-->
    				<prop key="hibernate.cache.use_query_cache">false</prop>
    				<prop key="hibernate.cache.use_second_level_cache">false</prop>
    				<prop key="hibernate.generate_statistics">true</prop>
    			</props>
    		</property>
    	</bean>
    
    	<!-- needed for Local JDBC Transaction -->
    	<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    
    	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    		<property name="entityManagerFactory" ref="entityManagerFactory" />
    		<property name="jpaDialect" ref="jpaDialect" />
    		<property name="dataSource" ref="dataSource" />
    	</bean>
    		
    		
    		 
    		<!-- <tx:annotation-driven transaction-manager="txManager"/>
    		<bean id="txManager"  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		    <property name="sessionFactory" ref="sessionFactory">
    		    </property>
    		 </bean>  -->
    		 
    </beans>
    Code:
    package com.cdis.flod.dao;
    
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    
    import org.hibernate.Session;
    
    
    
    public class AbstractDao<T> {
    
    	/** entity manager */
    	@PersistenceContext(unitName = "dbschema")
    	protected EntityManager entityManager;
    	
    	public Session getHibernateSession() {
    		return (Session) this.entityManager.getDelegate();
    	}
    	
    	public T save(T entity) {
    		return this.entityManager.merge(entity);
    	}
    	
    	
    	}
    Code:
    package com.cdis.flod.dao;
    
    import java.util.List;
    
    import org.hibernate.Query;
    import org.springframework.stereotype.Repository;
    
    import com.cdis.flod.common.RequestParameters;
    import com.cdis.flod.model.User;
    
    @Repository
    public class UserDao extends AbstractDao<User>{
    
    	
    	public User getUserByName(String userName) {
    		Query hqlQuery = getHibernateSession().createQuery("from User where userName=:name").
    			setString(RequestParameters.name.name(), userName);
    		
    		return (User)hqlQuery.setMaxResults(1).uniqueResult();	
    	}
    }
    Code:
    package com.cdis.flod.web;
    
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.Authentication;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import com.cdis.flod.common.RequestParameters;
    import com.cdis.flod.model.User;
    import com.cdis.flod.service.UserService;
    import com.cdis.flod.utils.Utils;
    
    @Controller
    public class LoginController {
    	
    	private final Log log = LogFactory.getLog(LoginController.class);
    	
    	
    	
    	@Autowired private UserService userService;
    	
    	@RequestMapping(value="/login",  method = RequestMethod.POST)
    	public String userLogin(@ModelAttribute("user") User user, BindingResult result, HttpServletRequest request,HttpServletResponse response, final ModelMap theModel){
    
    		log.info("Enter authentication");
    		
    		String userName = request.getParameter("userName");
    		String password = request.getParameter("password");
    		
    		user = userService.getUserByName(userName);
    		
    		if(userName.equals(user)){
    			return "user";
    		}else{
    		
    		return "failure";
    		}
    	}
    }
    Help resolving me this problem where is the mistake going on! please !

  • #2
    Why are you even using a session?! Use the entitymanager....

    Code:
    TypedQuery query = entitymanager.createTypedQuery("from User where userName=:name", User.class);
    query.setParameter("name", userName);
    return query.getSingleResult();
    If you use JPA then do use JPA...

    Comment


    • #3
      Session is closed!( Integration of Spring+Jpa/Hibernate)

      Hi Marten Deinum.
      It worked now.. I forgot to add this piece of code in my web.xml

      Code:
      <filter>
      		<filter-name>hibernateFilter</filter-name>
      			<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
      			
      			<init-param>
      				<param-name>entityManagerFactoryBeanName</param-name>
      				<param-value>entityManagerFactory</param-value>
      			</init-param>
      	</filter> 
      	
      	<filter-mapping>
      	  <filter-name>hibernateFilter</filter-name>
      	  <url-pattern>/*</url-pattern> 
      	</filter-mapping>
      This Worked by using Session

      And as you suggested me This piece of code started working for me

      Code:
      Query query = entityManager.createNativeQuery("select * from User where user_name=:name", User.class);
      		query.setParameter("name", userName);
      		return (User) query.getSingleResult()
      Any ways Thanks for your prompt Help!

      Comment


      • #4
        What I suggested is not to use the session... The code should work fine without a openentitymanagerinviewfilter. Unless you are doing some lazy-loading in your view (But that isn't what you hinted/pointed at).

        Comment

        Working...
        X