Hibernate中的问题:会话已关闭

时间:2017-03-15 08:01:19

标签: java mysql hibernate session

当我运行我在Eclipse中使用Hibernate执行的应用程序时,我遇到了这个问题。在这里,我向您展示了stacktrace和主要的java类。

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Session/EntityManager is closed
at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:332)
at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:126)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:647)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:102)
at vista.Principal$2.actionPerformed(Principal.java:124)
.
.
.

这里主要课程的部分有问题。

JList listaConsultas = new JList();
scroll.setViewportView(listaConsultas);

SessionFactory sesionfact1 = HibernateUtil.getSessionFactory();
Session sesion1 = sesionfact1.openSession();
Transaction tr = sesion1.beginTransaction();

JButton btnConsultar = new JButton("CONSULTAR");
btnConsultar.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

        Query queryAcogida = sesion1.createQuery("SELECT s FROM rah_histo_saip_acogida s WHERE fecharealiza BETWEEN :desde AND :hasta")
            .setParameter("desde",fechaDesde)
            .setParameter("hasta", fechaHasta);

        List<RahHistoSaipAcogida> listaAcogida = queryAcogida.list();

        queryAcogida.setFetchSize(10);
        DefaultListModel dlm = new DefaultListModel();
        dlm.addElement("----ACOGIDA DEL PACIENTE----");
        for(RahHistoSaipAcogida acog: listaAcogida){
            dlm.addElement(acog.toString());    
            listaConsultas.setModel(dlm);
        }
    }
});

tr.commit();
sesion1.close();
btnConsultar.setBounds(281, 113, 120, 23);
contentPane.add(btnConsultar);

1 个答案:

答案 0 :(得分:0)

public function startSession(Request $request)
    {
        event(new SiteAuth($session=parent::startSession($request)));
        return $session;
    }
声明时不会调用

。 这里真正的工作流程是:

public void actionPerformed(ActionEvent arg0) {

因此,当您执行操作时,交易将关闭,会话也会关闭。 您应该在执行的操作方法中添加会话操作,如下所示:

JList listaConsultas = new JList();
scroll.setViewportView(listaConsultas);

SessionFactory sesionfact1 = HibernateUtil.getSessionFactory();
Session sesion1 = sesionfact1.openSession();
Transaction tr = sesion1.beginTransaction();

JButton btnConsultar = new JButton("CONSULTAR");
tr.commit();
sesion1.close();
btnConsultar.setBounds(281, 113, 120, 23);
contentPane.add(btnConsultar);
... and later ...
actionPerformed(ActionEvent arg0)