- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我对 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/
我想做的是让 JTextPane 在 JPanel 中占用尽可能多的空间。对于我使用的 UpdateInfoPanel: public class UpdateInfoPanel extends JP
我在 JPanel 中有一个 JTextArea,我想将其与 JScrollPane 一起使用。我正在使用 GridBagLayout。当我运行它时,框架似乎为 JScrollPane 腾出了空间,但
我想在 xcode 中实现以下功能。 我有一个 View Controller 。在这个 UIViewController 中,我有一个 UITabBar。它们下面是一个 UIView。将 UITab
有谁知道Firebird 2.5有没有类似于SQL中“STUFF”函数的功能? 我有一个包含父用户记录的表,另一个表包含与父相关的子用户记录。我希望能够提取用户拥有的“ROLES”的逗号分隔字符串,而
我想使用 JSON 作为 mirth channel 的输入和输出,例如详细信息保存在数据库中或创建 HL7 消息。 简而言之,输入为 JSON 解析它并输出为任何格式。 最佳答案 var objec
通常我会使用 R 并执行 merge.by,但这个文件似乎太大了,部门中的任何一台计算机都无法处理它! (任何从事遗传学工作的人的附加信息)本质上,插补似乎删除了 snp ID 的 rs 数字,我只剩
我有一个以前可能被问过的问题,但我很难找到正确的描述。我希望有人能帮助我。 在下面的代码中,我设置了varprice,我想添加javascript变量accu_id以通过rails在我的数据库中查找记
我有一个简单的 SVG 文件,在 Firefox 中可以正常查看 - 它的一些包装文本使用 foreignObject 包含一些 HTML - 文本包装在 div 中:
所以我正在为学校编写一个 Ruby 程序,如果某个值是 1 或 3,则将 bool 值更改为 true,如果是 0 或 2,则更改为 false。由于我有 Java 背景,所以我认为这段代码应该有效:
我做了什么: 我在这些账户之间创建了 VPC 对等连接 互联网网关也连接到每个 VPC 还配置了路由表(以允许来自双方的流量) 情况1: 当这两个 VPC 在同一个账户中时,我成功测试了从另一个 La
我有一个名为 contacts 的表: user_id contact_id 10294 10295 10294 10293 10293 10294 102
我正在使用 Magento 中的新模板。为避免重复代码,我想为每个产品预览使用相同的子模板。 特别是我做了这样一个展示: $products = Mage::getModel('catalog/pro
“for”是否总是检查协议(protocol)中定义的每个函数中第一个参数的类型? 编辑(改写): 当协议(protocol)方法只有一个参数时,根据该单个参数的类型(直接或任意)找到实现。当协议(p
我想从我的 PHP 代码中调用 JavaScript 函数。我通过使用以下方法实现了这一点: echo ' drawChart($id); '; 这工作正常,但我想从我的 PHP 代码中获取数据,我使
这个问题已经有答案了: Event binding on dynamically created elements? (23 个回答) 已关闭 5 年前。 我有一个动态表单,我想在其中附加一些其他 h
我正在尝试找到一种解决方案,以在 componentDidMount 中的映射项上使用 setState。 我正在使用 GraphQL连同 Gatsby返回许多 data 项目,但要求在特定的 pat
我在 ScrollView 中有一个 View 。只要用户按住该 View ,我想每 80 毫秒调用一次方法。这是我已经实现的: final Runnable vibrate = new Runnab
我用 jni 开发了一个 android 应用程序。我在 GetStringUTFChars 的 dvmDecodeIndirectRef 中得到了一个 dvmabort。我只中止了一次。 为什么会这
当我到达我的 Activity 时,我调用 FragmentPagerAdapter 来处理我的不同选项卡。在我的一个选项卡中,我想显示一个 RecyclerView,但他从未出现过,有了断点,我看到
当我按下 Activity 中的按钮时,会弹出一个 DialogFragment。在对话框 fragment 中,有一个看起来像普通 ListView 的 RecyclerView。 我想要的行为是当
我是一名优秀的程序员,十分优秀!