Spring应用程序中的Hibernate DAO:Session对象自动永不关闭,为什么?

时间:2013-03-09 12:56:19

标签: java spring hibernate spring-mvc

我是Spring世界的新手,我使用Hibernate开发了一个简单的DAO,它在DB中的表上执行CRUD操作。

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

  

Session对象是轻量级的,旨在实现每个实例化   时间与数据库的交互需要。会话对象   不应该长时间保持开放,因为他们通常不会   线程安全,应根据需要创建和销毁它们。

在线阅读我已经明白,当调用@Transactional方法时,Spring会分别自动打开和关闭Session对象连接,并且当它关闭时我不需要手动处理这个事情:{{3 (在我输入CRUD方法时打开Session并在退出之前关闭它)

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

我使用了以下架构:我有一个名为 PersonDAO 接口,其中我声明了我希望在我的表上使用的CRUD方法,然后我实现了这个接口使用一个名为 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);
        }

}

正如你所看到的,我注入了SessionFactory对象的依赖关系,我用它来创建与数据库交互的Session对象,所有的CRUD方法和一个名为 getConnectionStatus()的方法只有返回连接状态(如果连接仍然保持打开和连接,则返回)

为了测试我的DAO,我实现了一个包含main()方法的 MainApp 类,并在其中测试了我的所有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操作),但似乎会话永远不会关闭。当我输入第一个被调用的CRUD方法时,它会自动打开但似乎在退出时不会关闭它(我在main的末尾使用对 getConnectionStatus()的调用来测试它( )方法)我很困惑......

所以我问你:

1)为什么Session不会自动关闭?它是如此糟糕,因为我在第一篇Hibernate文章中读到过同样的Session仍然保持开放状态?

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

TNX

安德烈

1 个答案:

答案 0 :(得分:3)

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

这很正常,因为这个方法就像DAO的其他方法一样:Spring拦截对方法的调用,打开会话,执行方法,因此,在方法内部,你得到一个开放的当前会话。

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