-1

I have read and find a lot of answers on the similar questions like

org.hibernate.HibernateException: No Session found for current thread

I have tried to add tx:annotation-driven transaction-manager="transactionManager">** but in result i had the error HTTP Status 500 - Servlet.init() for servlet mvc-dispatcher threw exception

How can i solve this problem. (Spring 3.2.0 + Hybernate 4.2.0.Final)

DetaIls.

web.xml

<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring MVC Application</display-name>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

dispercher-servlet.xml

<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"

       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.springapp.mvc"/>
    <context:annotation-config/>
    <tx:annotation-driven/>


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

    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan"
                  value="com.springapp.mvc.model" />
        <property name="hibernateProperties">
            <props>

                <prop key="hibernate.current_session_context_class">
                    org.springframework.orm.hibernate4.SpringSessionContext
                </prop>
                <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
            </props>

        </property>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test_student" />
        <property name="username" value="root" />
        <property name="password" value="181987" />
    </bean>

    <bean id="transactionManager"
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

HibernateSpitterDao

@Repository public class HibernateSpitterDao {

private SessionFactory sessionFactory;

@Autowired
public HibernateSpitterDao(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory; // Конструирует DAO
}


@Transactional(readOnly = false)
public void savestudent(Student student) {
   Session currentSession = sessionFactory.getCurrentSession();
   Transaction transaction = currentSession.beginTransaction();
   currentSession.save(student);
   transaction.commit();
     // Использует текущий сеанс
}

}

Controller

@Controller
@RequestMapping("/")
public class HelloController {

    private HibernateSpitterDao hibernateSpitterDao;

    @Autowired
    public HelloController(HibernateSpitterDao hibernateSpitterDao) {
        this.hibernateSpitterDao =  hibernateSpitterDao;
    }


    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        model.addAttribute("message", "Hello world!");
        model.addAttribute("Student",new Student());
        return "hello";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String printWelcome1(@Valid Student student,
                                BindingResult bindingResult) {
        hibernateSpitterDao.savestudent(student);
        return "hello";
    }
}

JSP

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>

<body>
    <h1>${message}</h1>
    <h3><strong>Start</strong></h3>
<div>
<sf:form method="post" modelAttribute="Student">

    <label for="login1"> Login </label>
    <sf:input path="name"  id="login1" />
    <p>  </p>
    <label for="pass"> password </label>
    <sf:password path="password"  id="pass" />
    <p></p>

    <button type="submit">Registration</button>

</sf:form>

</div>
</body>
Community
  • 1
  • 1
Mikhail
  • 2,690
  • 4
  • 28
  • 43

5 Answers5

2

You need to update the value you have in your dispercher-servlet.xml

Use the following value for session context.

<prop key="hibernate.current_session_context_class">thread</prop>

thread is short for org.hibernate.context.internal.ThreadLocalSessionContext

Please check this link for more detailed information.

http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#architecture-current-session

sendon1982
  • 9,982
  • 61
  • 44
1

You have @Transactional annotation on your saveStudent dao method but also try and create a transaction manually in your dao method do one or other like so:

@Transactional(readOnly = false)
public void savestudent(Student student) {
    Session currentSession = sessionFactory.getCurrentSession();
    currentSession.save(student);
}

Also ensure that your dao class lives within or below the package that is specified in your component-scan tag otherwise the annotations will not be picked up by spring. Alternatively you could add a bean definition for your dao in the spring wiring that will also allow spring to do something with its annotations.

jcmwright80
  • 2,599
  • 1
  • 13
  • 15
1

I had the same problem.

I was using annotation based configuration, I have configured sessionfactory, datasource and transaction manager every thing. but I did not give @EnableTransactionManagement annotation at AppConfig class.

The code looks like below after adding the transaction annotation.

@Configuration
@ComponentScan("com.bmp.*")
@EnableWebMvc
@PropertySource("classpath:${env}.properties")
@EnableTransactionManagement
public class AppConfig {
-----
}

The above annotations resolved my problem.

Anil
  • 337
  • 2
  • 10
0

Solution 1. Delete Constructor in Repository class. 2. Delete transactions in Repository class.

Mikhail
  • 2,690
  • 4
  • 28
  • 43
0

Please use the @Repository annotation in dao layer and @Transnational on top of save student

Babu Babu
  • 11
  • 1