简体   繁体   中英

Hibernate 4 and Spring 4 HibernateException: No Session found for current thread

I've looked trough all of the other posts regarding this issue and I can't seem to fix it. Everytime I call a method from my service, I get the No Session found exception.

Here is my code:

applicationContext.xml

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

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>/WEB-INF/database.properties</value>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.baskettracer.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

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

Dispatcher-Servlet:

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

    <context:component-scan base-package="com.baskettracer" />

    <mvc:annotation-driven />

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

    <mvc:resources mapping="/resources/**" location="/resources/" />


</beans>

PersonDAO:

package com.baskettracer.dao;

import com.baskettracer.entity.Person;

/**
 *
 * @author 11302801
 */
public interface PersonDAO extends AbstractDAO<Person, String> {

    void updatePassword(String pw);
    String hash(String s);
    String sha1(String s);
    String md5(String s);
}

PersonDAOImpl:

package com.baskettracer.dao.impl;

import com.baskettracer.dao.PersonDAO;
import com.baskettracer.entity.Person;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Cornel
 */
@Repository
public class PersonDAOImpl extends AbstractDAOImpl<Person, String> implements PersonDAO {

    protected PersonDAOImpl() {
        super(Person.class);
    }

    @Override
    public void updatePassword(String pw) {
        String hql = "update Person set wachtwoord = :pw";
        Query q = getCurrentSession().createQuery(hql);
        q.setParameter("pw", hash(pw));
    }

    @Override
    public String hash(String s) {

        /*public function encrypt_password($password) {
         $salt = sha1(md5($password));
         $encryptedPassword = md5($password . $salt);

         return $encryptedPassword;*/
        return s;
    }

    @Override
    public String sha1(String s) {
        java.security.MessageDigest d = null;
        try {
            d = java.security.MessageDigest.getInstance("SHA-1");
            d.reset();
            d.update(s.getBytes("UTF-8"));

            return d.digest().toString();
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) {
            return null;
        }
    }

    @Override
    public String md5(String s) {
        java.security.MessageDigest d = null;
        try {
            d = java.security.MessageDigest.getInstance("MD5");
            d.reset();
            d.update(s.getBytes("UTF-8"));

            return d.digest().toString();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
            return null;
        }
    }
}

PersonServiceImpl:

    package com.baskettracer.service.impl;

import com.baskettracer.dao.PersonDAO;
import com.baskettracer.entity.Person;
import com.baskettracer.service.PersonService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Cornel
 */

@Service("personService")
@Transactional
public class PersonServiceImpl implements PersonService{

    @Autowired
    private PersonDAO personDAO;

    @Override
    @Transactional(readOnly = true)
    public Person get(int id) {
        return personDAO.get(id);
    }

    @Override
    public List<Person> get() {
        return personDAO.get();
    }

    @Override
    @Transactional(readOnly = false)
    public void save(Person p) {
        personDAO.save(p);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(Person p) {
        personDAO.delete(p);
    }

}

Person:

package com.baskettracer.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;


/**
 *
 * @author 11302801
 */
@Entity
@Table(name = "personen")
public class Person {
    private Integer id;
    private String firstname;
    private String lastname;
    private String username;
    private Date dob;
    private String gender;
    private boolean available;
    private boolean injured;
    private boolean suspended;

    public Person(){};

    public Person(String firstname, String lastname, Date dob, String gender, String username, boolean available, boolean injured, boolean suspended){
        this.firstname = firstname;
        this.lastname = lastname;
        this.dob = dob;
        this.gender = gender;
        this.username = username;
        this.available = available;
        this.injured = injured;
        this.suspended= suspended;
    }

    @Id
    @GeneratedValue
    @Column(name="persoonid")
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Column(name="voornaam")
    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    @Column(name="achternaam")
    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    @Column(name="gebruikersnaam")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Column(name="geboortedatum")
    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    @Column(name="geslacht")
    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Column(name="beschikbaar")
    public boolean isAvailable() {
        return available;
    }

    public void setAvailable(boolean available) {
        this.available = available;
    }

    @Column(name="gekwetst")
    public boolean isInjured() {
        return injured;
    }

    public void setInjured(boolean injured) {
        this.injured = injured;
    }

    @Column(name="geschorst")
    public boolean isSuspended() {


  return suspended;
}

public void setSuspended(boolean suspended) {
    this.suspended = suspended;
}

}

Main:

package com.baskettracer.controller;

import com.baskettracer.entity.Person;
import com.baskettracer.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class Main {

    @Autowired
    private PersonService personService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(ModelMap map) {
        //Person p = personService.get(1);

        return "home";
    }
}

Any help would be greatly appreciated!

Regards, Cornel Janssen

adjusted the

<context:component-scan base-package="com.baskettracer" /> 

to

<context:component-scan base-package="com.baskettracer.controller" /> 

in my dispatcher and inserted

<context:component-scan base-package="com.baskettracer">
        <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan> 

into my applicationContext. now it works!! Thanks all!

You need to add an @Transactional annotation somewhere. You could add it to the PersonDAOImpl class. This will make sure a session is opened and everything is cleaned up when it's done.

If you have an implementation for the PersonService you could add it to the class or any of the methods therein as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM