1
votes

I am new to spring and was making a login page using spring and hibernate but at the time of getting sessionFactory it is giving me this error -

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

I am struggling from 1 day. How can i resolve it. My Code is -

UserDao -

package com.mogae.springLogin.db.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.hibernate.SessionFactory;

import com.mogae.springLogin.entities.User;

public class UserDao {

    private static Logger LOGGER = Logger.getLogger(UserDao.class.getName());
    private SessionFactory sessionFactory;



    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @SuppressWarnings("unchecked")
    public User findUser(String username,String password)
    {
        List<User> users = new ArrayList<User>();
        try{
    //      LOGGER.info("session = "+getFactory().getCurrentSession().isOpen());
        LOGGER.info("login for username = "+username);
        users = getSessionFactory().getCurrentSession().createQuery("from user_data where username =? and password = ?").setParameter(0, username).setParameter(1, password).list();
        }catch(Exception e){
            e.printStackTrace();
        }

        if(users.size()>0)
            return users.get(0);
        else
            return null;
    }

}

Controller class is -

package com.mogae.springLogin.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.mogae.springLogin.db.dao.UserDao;
import com.mogae.springLogin.entities.User;

@Controller
@RequestMapping("/login")
public class LoginController {

@Autowired
private UserDao userDao;


    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView loginUser(@RequestParam("username") String username,
            @RequestParam("password") String password) {
        User user = userDao.findUser(username, password);
        if (user != null)
            return new ModelAndView("jsp/result", "message",
                    "successfully login with user = " + username);
        else
            return new ModelAndView("jsp/index", "message",
                    "invalid login");
    }

}

applicationContext.xml is -

<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="org.postgresql.Driver"></property>
        <property name="url" value="jdbc:postgresql://localhost:5432/testdb"></property>
        <property name="username" value="postgres"></property>
        <property name="password" value="root"></property>
    </bean>

    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>

        <property name="mappingResources">
            <list>
                <value>user.hbm.xml</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>


    <bean id="userDao" class="com.mogae.springLogin.db.dao.UserDao">
         <property name="sessionFactory" ref="mySessionFactory"></property>
    </bean>


</beans>  

spring-servlet.xml is-

<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:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.0.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

<context:component-scan base-package="com.mogae.springLogin.controllers" />

<!-- Configuration defining views files -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
</bean>
</beans>

My web.xml is -

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>springLogin</display-name>
    <welcome-file-list>
        <welcome-file>jsp/index.jsp</welcome-file>
    </welcome-file-list>
    <!-- Spring Configuration -->
        <servlet>
            <servlet-name>spring</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>spring</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
     <context-param>
        <param-name>log4jXMLpath</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml, /WEB-INF/applicationContext.xml</param-value>
        </context-param>
        <listener>
            <listener-class>
                org.springframework.web.context.ContextLoaderListener
            </listener-class>
        </listener>
</web-app>

My Stack-Trace is -

2015-01-18 18:22:57,346 DEBUG [org.springframework.orm.hibernate3.SessionFactoryUtils] Opening Hiber
nate Session
2015-01-18 18:22:57,836 DEBUG [org.springframework.orm.hibernate3.SessionFactoryUtils] Closing Hiber
nate Session
org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not a
llow creation of non-transactional one here
        at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionConte
xt.java:63)
        at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:574)
        at com.mogae.springLogin.db.dao.UserDao.findUser(UserDao.java:35)
        at com.mogae.springLogin.controllers.LoginController.loginUser(LoginController.java:24)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(Handl
erMethodInvoker.java:710)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(
HandlerMethodInvoker.java:167)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandl
erMethod(AnnotationMethodHandlerAdapter.java:414)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(Anno
tationMethodHandlerAdapter.java:402)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647
)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.j
ava:305)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)

        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:928)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987
)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.jav
a:539)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:298)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
2015-01-18 18:22:58,166 DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory]
 Invoking afterPropertiesSet() on bean with name 'jsp/index'
2015-01-18 18:22:58,169 DEBUG [org.springframework.web.servlet.DispatcherServlet] Rendering view [or
g.springframework.web.servlet.view.JstlView: name 'jsp/index'; URL [/jsp/index.jsp]] in DispatcherSe
rvlet with name 'spring'
2015-01-18 18:22:58,170 DEBUG [org.springframework.web.servlet.view.JstlView] Added model object 'me
ssage' of type [java.lang.String] to request in view with name 'jsp/index'
2015-01-18 18:22:58,186 DEBUG [org.springframework.web.servlet.view.JstlView] Forwarding to resource
 [/jsp/index.jsp] in InternalResourceView 'jsp/index'
2015-01-18 18:22:58,215 DEBUG [org.springframework.web.servlet.DispatcherServlet] Successfully compl
eted request
1
@PaulVargas I checked that now i am taking applicationContext.xml in conext-param in web.xml. but now a new error is coming in my same code. hibernate session bound to thread and configuration does not allow creationAmit Das
post the actual stack trace?ConMan
also trying adding this property to your hibernate config: <property name="current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>ConMan
You need a transaction to use Hibernate. Read the documentation about transactions in the Spring documentation: docs.spring.io/spring/docs/current/spring-framework-reference/…JB Nizet

1 Answers

0
votes

As far as I know Spring look for interfaces to Autowired beans, so I think that you have to declare an interface for your class userDao, and in the implementation of it you put this annotation @Repository("userDao") like this

public interface UserDao {
   .......
}

@Repository("userDao")
public class UserDaoImpl implements UserDao {
 ........
}