如何解决异常org.hibernate.SessionException:Session已经关闭

时间:2014-09-06 10:44:06

标签: java hibernate

我是Hibernate的新手,我自己做了一些编程,直到遇到这个问题。我试图将一个对象添加到数据库中,然后从数据库中检索该对象。我试过在线寻求帮助,但无法解决此错误。任何帮助,将不胜感激。我得到的堆栈跟踪:

Exception in thread "main" org.hibernate.SessionException: Session was already closed
    at org.hibernate.internal.SessionImpl.close(SessionImpl.java:359)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:356)
    at com.sun.proxy.$Proxy6.close(Unknown Source)
    at com.project.hibernate.HibernateTest.main(HibernateTest.java:39) 

这是我到目前为止编写的代码:

HiberateTest.java

public class HibernateTest {

    public static void main(String[] args) {
        Logger log = LoggerFactory.getLogger(HibernateTest.class);

        UserDetails user = new UserDetails();
        log.debug("Testing");
        user.setUserId(1);
        user.setUserName("First User");
        user.setAddress("First user's address");
        user.setJoinedDate(new Date());
        user.setDescription("user description");

        Configuration configuration = new Configuration();
        configuration.configure("com/project/hibernate/hibernate.cfg.xml");
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        Session session = sessionFactory.getCurrentSession();

        //add object
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
        session.close();

        //retrieve object that was added
        session = sessionFactory.openSession();
        user = null;
        session.beginTransaction();
        user =  (UserDetails) session.get(UserDetails.class,1);
        session.getTransaction().commit();
        session.close();

        System.out.println("User Name retrieved is " + user.getUserName());

    }
}

UserDetails.java

@Entity
@Table(name="USER_DETAILS")
public class UserDetails {
    @Id
    private int userId;

    private String userName;
    @Temporal(TemporalType.DATE)

    private Date joinedDate;
    private String address;

    private String description;

    public Date getJoinedDate() {
        return joinedDate;
    }
    public void setJoinedDate(Date joinedDate) {
        this.joinedDate = joinedDate;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }

}

hibernate.cfg.xml中

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:~/test</property>
        <property name="connection.username">sa</property>
        <property name="connection.password">v15t4.</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <property name="hibernate.current_session_context_class">
            org.hibernate.context.internal.ThreadLocalSessionContext
        </property>

        <mapping class="com.project.hibernate.UserDetails" />

    </session-factory>

</hibernate-configuration>

2 个答案:

答案 0 :(得分:6)

我设法通过删除

来解决问题
Session session = sessionFactory.getCurrentSession()

openSession()

答案 1 :(得分:0)

保存对象时不要关闭会话。 尝试删除session.close();