我是 Spring 世界的新手,我使用 Hibernate 开发了一个简单的 DAO,它在数据库中的表上执行 CRUD 操作。
在这里阅读:http ://www.tutorialspoint.com/hibernate/hibernate_sessions.htm我可以读到:
Session 对象是轻量级的,设计为在每次需要与数据库交互时实例化。会话对象不应长时间保持打开状态,因为它们通常不是线程安全的,应根据需要创建和销毁它们。
在线阅读我了解到,当调用@Transactional 方法和关闭它时,Spring 会分别自动打开和关闭 Session 对象连接,我不需要像这里那样手动处理这件事:http://www. tutorialspoint.com/hibernate/hibernate_examples.htm(当我进入 CRUD 方法时打开会话并在退出之前关闭它)
我的 DAO 似乎运行良好(在数据库上正确执行所有定义的 CRUD 操作)但似乎会话从未关闭。当我进入第一个调用的 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 文章中读到的那样糟糕吗?有相同的会话仍然保持打开状态?
2)使用这种架构(接口及其实现)如何在退出CRUD方法时自动关闭会话?
肿瘤坏死因子
安德烈亚