简体   繁体   中英

Problems in Spring + Hibernate application: org.hibernate.HibernateException: No Session found for current thread

I am studying how to integrate Spring Framework with Hibernate to create my DAO object

I have some problem executing a Read operation from CRUD operation set.

I have this class that implement my DAO object:

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);   
}   

}

And I have the following main class that is used ad tesing class:

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());

}
}

This testing class first insert a new record in my database table, and ok...this work well (the new row is correctly inserted in the table)

The try to extract a row that have a specific id. Here I am having some problem because when try to get the object throws the following Exception:

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)**

What is the problem? Is it my strategy to get the object right?

Tnx

Andrea

Your problem is here:

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

The method getCurrentSession() returns the session bound to the current context. You cannot use this method in your setup, you need to use openSession() as in your addPerson method. So you need to do:

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

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