java - Spring 应用程序中的 Hibernate DAO : the Session object is automatically never closed, 为什么?

标签 java spring hibernate spring-mvc

我对 Spring 世界还是个新手,我已经使用 Hibernate 开发了一个简单的 DAO,可以在数据库中的表上执行 CRUD 操作。

在这里阅读:http://www.tutorialspoint.com/hibernate/hibernate_sessions.htm我可以读到:

The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed.

在线阅读我了解到,当调用 @Transactional 方法和关闭它时,Spring 会分别自动打开和关闭 Session 对象连接,我不需要像这里那样手动处理这件事:http://www.tutorialspoint.com/hibernate/hibernate_examples.htm (当我进入 CRUD 方法时打开 session 并在退出之前关闭它)

我的 DAO 似乎运行良好(在数据库上正确执行所有定义的 CRUD 操作),但似乎 session 从未关闭。当我进入第一个调用的 CRUD 方法时它会自动打开,但退出时似乎不会关闭它

我使用了以下架构:我有一个名为 PersonDAO接口(interface),其中我声明了我希望在表上使用的 CRUD 方法,然后实现该接口(interface)使用名为 PersonDAOImpl2 的具体类来实现 Hibernate 声明的方法。

这是我的PersonDAOImpl2类代码:

package org.andrea.myexample.HibernateOnSpring.dao;

import java.util.List;

import org.andrea.myexample.HibernateOnSpring.entity.Person;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional
public class PersonDAOImpl2 implements PersonDAO {

    // Factory per la creazione delle sessioni di Hibernate:

    private SessionFactory sessionFactory;

        // Metodo Setter per l'iniezione della dipendenza della SessionFactory:

        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
            System.out.println("Ho iniettato la SessionFactory: " + sessionFactory);

        }

        public String getConnectionStatus(){

            return " Aperta: " + sessionFactory.getCurrentSession().isOpen() + " Connessa: " + sessionFactory.getCurrentSession().isConnected();
        }


        /** CREATE CRUD Operation:
         * Aggiunge un nuovo record rappresentato nella tabella rappresentato
         * da un oggetto Person
         */
        @Transactional(readOnly = false)
        public Integer addPerson(Person p) {

            System.out.println("Inside addPerson()");
            System.out.println("Connessione aperta: " + sessionFactory.getCurrentSession().isOpen());
            System.out.println("E' connesa:" + sessionFactory.getCurrentSession().isConnected());

            Integer personID = personID = (Integer) sessionFactory.getCurrentSession().save(p);

            return personID;

        }

        // READ CRUD Operation (legge un singolo record avente uno specifico id):
        @Transactional
        public Person getById(int id) {

            Person retrievedPerson = null;

            System.out.println("Inside getById()");

            System.out.println("Inside addPerson()");
            System.out.println("Connessione aperta: " + sessionFactory.getCurrentSession().isOpen());
            System.out.println("E' connesa:" + sessionFactory.getCurrentSession().isConnected());

            retrievedPerson = (Person) sessionFactory.getCurrentSession().get(Person.class, id);

            return retrievedPerson;

        }

        // READ CRUD Operation (recupera la lista di tutti i record nella tabella):
        @SuppressWarnings("unchecked")
        @Transactional
        public List<Person> getPersonsList() {

            System.out.println("Inside getPersonsList()");
            List<Person> personList = null;

            Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Person.class);
            personList = criteria.list();

            return personList;
        }

        // DELETE CRUD Operation (elimina un singolo record avente uno specifico id):
        @Transactional
        public void delete(int id) {
            System.out.println("Inside delete()");

            Person personToDelete = getById(id);
            sessionFactory.getCurrentSession().delete(personToDelete);
        }

        // UPDATE CRUD OPERATION (aggiorna un determinato record rappresentato da un oggetto)
        @Transactional
        public void update(Person personToUpdate) {

            System.out.println("Inside update()");

            sessionFactory.getCurrentSession().update(personToUpdate);
        }

}

如您所见,我注入(inject)了 SessionFactory 对象的依赖项,该对象用于创建与数据库交互的 Session 对象、所有 CRUD 方法和名为 getConnectionStatus() 的方法返回连接的状态(如果连接仍然保持打开和连接状态则返回)

为了测试我的 DAO,我实现了一个 MainApp 类,其中包含 main() 方法,并在其中测试我的所有 CRUD 操作,这一个:

package org.andrea.myexample.HibernateOnSpring;

import java.util.List;
import java.util.Iterator;

import org.andrea.myexample.HibernateOnSpring.dao.PersonDAO;
import org.andrea.myexample.HibernateOnSpring.entity.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

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

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

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

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

        dao.addPerson(persona1);

        System.out.println("persona1 salvata nel database");
        System.out.println("persona1 ha id: " + persona1.getPid());

        System.out.println("Recupero l'oggetto Person avente id: "
                + persona1.getPid());

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

        System.out.println("nome: " + personRetrieved.getFirstname());
        System.out.println("cognome: " + personRetrieved.getLastname());
        System.out.println("ID: " + personRetrieved.getPid());


        System.out.println("Aggiungo altri 2 record nella tabella: ");

        Person persona2 = new Person();
        Person persona3 = new Person();

        persona2.setFirstname("Mario");
        persona2.setLastname("Rossi");
        persona3.setFirstname("Paolino");
        persona3.setLastname("Paperino");

        dao.addPerson(persona2);
        dao.addPerson(persona3);

        List<Person> listaPersone = dao.getPersonsList();

        for (Iterator iterator = listaPersone.iterator(); iterator.hasNext();) {
            Person persona = (Person) iterator.next();
            System.out.print("Nome: " + persona.getFirstname());
            System.out.print(" Cognome: " + persona.getLastname());
            System.out.println("  ID: " + persona.getPid());
        }


        System.out.println("Elimina il primo record dalla tabella");

        Person firstPerson = listaPersone.get(0);
        System.out.println("Persona da eliminare: " + firstPerson);

        dao.delete(firstPerson.getPid());

        listaPersone = dao.getPersonsList();

        for (Iterator iterator = listaPersone.iterator(); iterator.hasNext();) {
            Person persona = (Person) iterator.next();
            System.out.print("Nome: " + persona.getFirstname());
            System.out.print(" Cognome: " + persona.getLastname());
            System.out.println("  ID: " + persona.getPid());
        }

        System.out.println("Aggiorna il primo record della tabella:");

        firstPerson = listaPersone.get(0);

        System.out.println("Persona da aggiornare: " + firstPerson);
        System.out.print("Nome: " + firstPerson.getFirstname());
        System.out.print(" Cognome: " + firstPerson.getLastname());
        System.out.println("  ID: " + firstPerson.getPid());

        System.out.println("CAMBIO DEI DATI:");

        firstPerson.setFirstname("Gatto");
        firstPerson.setLastname("Silvestro");

        System.out.println("Nuovi dati: " + firstPerson);
        System.out.print("Nome: " + firstPerson.getFirstname());
        System.out.print(" Cognome: " + firstPerson.getLastname());
        System.out.println("  ID: " + firstPerson.getPid());

        System.out.println("UPDATING !!!");

        dao.update(firstPerson);

        listaPersone = dao.getPersonsList();

        for (Iterator iterator = listaPersone.iterator(); iterator.hasNext();) {
            Person persona = (Person) iterator.next();
            System.out.print("Nome: " + persona.getFirstname());
            System.out.print(" Cognome: " + persona.getLastname());
            System.out.println("  ID: " + persona.getPid());
        }

        System.out.println(dao.getConnectionStatus()); 

    }

}

这是我的 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:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd        
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/SpringTestDb" />
        <property name="username" value="root" />
        <property name="password" value="aprile12" />
        <property name="initialSize" value="2" />
        <property name="maxActive" value="5" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="org.andrea.myexample.HibernateOnSpring.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
    </bean>

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

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

    <bean id="personDAOImpl2" class="org.andrea.myexample.HibernateOnSpring.dao.PersonDAOImpl2" >
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- Register @Autowired annotation -->
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
</beans>

我的 DAO 似乎运行良好(在数据库上正确执行所有定义的 CRUD 操作),但 session 似乎从未关闭。当我进入第一个调用的 CRUD 方法时,它会自动打开,但退出时似乎不会关闭它(我已经在 main( 末尾调用 getConnectionStatus() 进行了测试) )方法),我对此感到困惑......

所以我问你:

1) 为什么Session没有自动关闭?正如我在第一篇 Hibernate 文章中读到的那样,相同的 session 仍然保持打开状态吗?

2)使用这种架构(接口(interface)及其实现)如何在退出 CRUD 方法时自动关闭 session ?

Tnx

安德里亚

最佳答案

如果我理解正确的话,您正在调用 DAO 的 getConnectionStatus(),并且它返回 session 已打开。

这很正常,因为这个方法就像 DAO 的其他方法一样:Spring 拦截对该方法的调用,打开一个 session ,执行该方法,因此,在该方法内,您将获得一个打开的当前 session 。

请注意,虽然方法上没有 @Transactional 注释,但它是事务性的,因为您还在类本身上放置了 @Transactional 注释,使其所有方法都具有事务性。

关于java - Spring 应用程序中的 Hibernate DAO : the Session object is automatically never closed, 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15310918/

相关文章:

java - 底层数据处理程序接收数据时如何在 Activity 上触发 UI 更新

java - Spring Boot 配置处理器,前缀的重复@ConfigurationProperties 定义

java - 在基于 java 的配置中设置 Bean 属性,无需构造函数或 setter

一旦数据库被退回, hibernate 就不会重新连接

hibernate - 回滚是否终止 session ?

java - Android 按钮监听器代码最小化所需

java - Spring Boot不读取application.properties

java - @OneToOne 和 @JoinColumn 只保存 UUID 而不是整个对象

java - Spring JPA/Hibernate 未更新到数据库以在保存时更改 @Entity 的 boolean 值

java - 打印java中所有异常位置