Spring + Hibernate应用程序中的问题:org.hibernate.HibernateException:找不到当前线程的Session

时间:2013-02-23 18:09:40

标签: java spring hibernate spring-mvc

我正在研究如何将Spring Framework与Hibernate集成以创建我的DAO对象

我在从CRUD操作集执行读操作时遇到一些问题。

我有这个实现我的DAO对象的类:

package org.andrea.myexample.HibernateOnSpring.dao;

import org.andrea.myexample.HibernateOnSpring.entity.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

public class PersonDAOImpl implements PersonDAO{

private SessionFactory sessionFactory;

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

// Metodo che inserisce un nuovo record nella tabella person
@Transactional(readOnly=false)
public void addPerson(Person p) {
    Session session = sessionFactory.openSession();
    session.save(p);
    session.close();        
}

/* Metodo che recupera un record, rappresentante uno studente, avente uno 
 * specifico id dalla tabella.
 * 
 * @param L'id dello studente
 * @see org.andrea.myexample.myJdbcSpringExample.StudentDAO#getStudent(java.lang.Integer)
 */
public Person getById(int id){
    Session session = sessionFactory.openSession();
    return (Person) sessionFactory.getCurrentSession().get(Person.class, id);   
}   

}

我有以下用于广告测试类的主要课程:

package org.andrea.myexample.HibernateOnSpring;

import org.andrea.myexample.HibernateOnSpring.dao.PersonDAO;
import org.andrea.myexample.HibernateOnSpring.dao.PersonDAOImpl;
import org.andrea.myexample.HibernateOnSpring.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

public static void main( String[] args ){

    ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
    System.out.println("Contesto recuperato: " + context);

    Person persona1 = new Person();

    persona1.setFirstname("Pippo");
    persona1.setLastname("Blabla");
    //persona1.setPid(1);

    System.out.println("Creato persona1: " + persona1);

    PersonDAO dao = (PersonDAO) context.getBean("personDAOImpl");

    System.out.println("Creato dao object: " + dao);

    dao.addPerson(persona1);

    System.out.println("persona1 salvata nel database");

    Person personaEstratta = dao.getById(persona1.getPid());

    System.out.println("Persona con id: " + personaEstratta.getPid() + " estratta dal DB");
    System.out.println("Dati persona estratta:");
    System.out.println("Nome: " + personaEstratta.getFirstname());
    System.out.println("Cognome: " + personaEstratta.getLastname());

}
}

此测试类首先在我的数据库表中插入一条新记录,然后确定...这项工作正常(新行正确插入表中)

尝试提取具有特定ID的行。这里我遇到了一些问题,因为在尝试获取对象时会抛出以下异常:

Contesto recuperato: org.springframework.context.support.ClassPathXmlApplicationContext@11ba3c1f: startup date [Sat Feb 23 19:07:42 CET 2013]; root of context hierarchy
Creato persona1: org.andrea.myexample.HibernateOnSpring.entity.Person@777dcf23
Creato dao object: org.andrea.myexample.HibernateOnSpring.dao.PersonDAOImpl@3f12ccc4
persona1 salvata nel database
**
Exception in thread "main" 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:978)
    at org.andrea.myexample.HibernateOnSpring.dao.PersonDAOImpl.getById(PersonDAOImpl.java:31)
    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:601)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198)
    at sun.proxy.$Proxy11.getById(Unknown Source)
    at org.andrea.myexample.HibernateOnSpring.App.main(App.java:33)**

有什么问题?我的策略是让对象正确吗?

TNX

安德烈

1 个答案:

答案 0 :(得分:5)

你的问题在这里:

public Person getById(int id){
    Session session = sessionFactory.openSession();
    return (Person) sessionFactory.getCurrentSession().get(Person.class, id);   
} 

方法getCurrentSession()返回绑定到当前上下文的会话。您无法在设置中使用此方法,您需要在openSession()方法中使用addPerson。所以你需要这样做:

public Person getById(int id){
    Session session = sessionFactory.openSession(); 
    try {
      return (Person) session.get(Person.class, id);
    } finally {
      session.close();
    }    
}