工程结构

问题描述

在工程中通过spring aop的方式配置事务,使用hibernate做持久化。在代码实现中使用hibernate persit()方法插入数据到数据库,使用hibernate update()方法更新数据。问题是执行这两个方法没有报错,但是也没有插入数据或者更新数据。

原因

hibernate persist()以及update()方法只有事务执行flush()或者commit()方法,才将数据写入数据库。详细内容可以阅读博客:http://www.cnblogs.com/xiaoheike/p/5374613.html。使用spring aop配置的事务,在方法运行结束之后会运行commit()方法。程序实例可以看PersonDAOImpl.java(实现方法)小结,重点原因在于spring aop事务与session自己创建的事务是两个不同的事务,虽然最后spring aop 配置的事情 commit,但是session对象的事务并没有调用commit。以下是实例程序。

事务配置(applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/Testdb" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean> <!-- Hibernate 4 SessionFactory Bean definition -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<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">true</prop>
<prop key="hiberante.format_sql">true</prop>
</props>
</property>
<!-- hibernate配置文件放置位置,这个配置文件似乎也没有多大的作用了 -->
<property name="configLocations">
<list>
<value>
classpath:/hibernate.cfg.xml
</value>
</list>
</property>
</bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <tx:advice id="personServiceTxAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 表达式中的这些方法会执行如下的规则 -->
<tx:method name="delete*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" />
<tx:method name="update*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" />
<tx:method name="save*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" />
<tx:method name="*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" />
</tx:attributes>
</tx:advice> <aop:config>
<aop:pointcut id="personServiceTxPointcut" expression="execution(* com.journaldev.dao.PersonDAO.*(..))" />
<aop:advisor id="personServiceTxAdvisor" advice-ref="personServiceTxAdvice" pointcut-ref="personServiceTxPointcut" />
</aop:config> <bean id="personDAO" class="com.journaldev.dao.PersonDAOImpl">
<property name="sessionFactory1" ref="sessionFactory" />
<property name="sessionFactory2" ref="sessionFactory" />
</bean>
</beans>

PersonDAOImpl.java(实现方法)

package com.journaldev.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction; import com.journaldev.model.Person; public class PersonDAOImpl implements PersonDAO { private SessionFactory sessionFactory1;
private SessionFactory sessionFactory2; public void setSessionFactory1(SessionFactory sessionFactory1) {
this.sessionFactory1 = sessionFactory1;
} public void setSessionFactory2(SessionFactory sessionFactory2) {
this.sessionFactory2 = sessionFactory2;
} public void save1(Person person) {
Session session1 = this.sessionFactory1.openSession();
session1.persist(person);
session1.close();
} public void save2(Person person) {
Session session1 = this.sessionFactory1.openSession();
Session session2 = sessionFactory2.openSession();
Transaction tx = session2.beginTransaction();
session1.persist(person);
tx.commit();
session2.close();
session1.close();
} public void save3(Person person) {
Session session1 = this.sessionFactory1.openSession();
Transaction tx = session1.beginTransaction();
session1.persist(person);
tx.commit();
session1.close();
} @SuppressWarnings("unchecked")
public List<Person> list() {
Session session = this.sessionFactory1.openSession();
List<Person> personList = session.createQuery("from Person").list();
session.close();
return personList;
} public Person findOne(Integer id) {
Session session = this.sessionFactory1.openSession();
Person p = (Person) session.get(Person.class, id);
session.close();
return p;
} public void delete(Person person) {
Session session = this.sessionFactory1.openSession();
session.delete(person);
session.close();
} public void update1(Person person) {
Session session = this.sessionFactory1.openSession();
session.update(person);
session.close();
} public void update2(Person person) {
Session session1 = this.sessionFactory1.openSession();
Session session2 = this.sessionFactory1.openSession();
Transaction tx = session2.beginTransaction();
session1.update(person);
tx.commit();
session2.close();
session1.close();
} public void update3(Person person) {
Session session1 = this.sessionFactory1.openSession();
Transaction tx = session1.beginTransaction();
session1.update(person);
tx.commit();
session1.close();
}
}

测试类

package com.journaldev.main;

import java.util.List;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.journaldev.dao.PersonDAO;
import com.journaldev.model.Person; public class SpringHibernateMain { public static void main(String[] args) {
test1();
test2();
test3();
} public static void test1() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDAO personDAO = context.getBean(PersonDAO.class);
System.out.println("=================save1()==================");
// 增加一条数据
Person person = new Person();
person.setName("Pankaj");
person.setCountry("India");
personDAO.save1(person);
System.out.println("================listAll()===================");
// 检索所有数据
List<Person> list = personDAO.list();
for (Person p : list) {
System.out.println("所有记录:" + p);
}
System.out.println("================update1()===================");
// 更新一条Person记录
person.setCountry("zhongguo");
personDAO.update1(person);
System.out.println("更新一条记录India-->zhongguo:" + personDAO.findOne(person.getId()));
System.out.println("================delete()===================");
// 删除一条Person记录
personDAO.delete(person); context.close();
} public static void test2() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDAO personDAO = context.getBean(PersonDAO.class);
System.out.println("=================save3()==================");
// 增加一条数据
Person person = new Person();
person.setName("Pankaj");
person.setCountry("India");
personDAO.save1(person);
System.out.println("================listAll()===================");
// 检索所有数据
List<Person> list = personDAO.list();
for (Person p : list) {
System.out.println("所有记录:" + p);
}
System.out.println("================update2()===================");
// 更新一条Person记录
person.setCountry("zhongguo");
personDAO.update1(person);
System.out.println("更新一条记录India-->zhongguo:" + personDAO.findOne(person.getId()));
System.out.println("================delete()===================");
// 删除一条Person记录
personDAO.delete(person); context.close();
} public static void test3() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDAO personDAO = context.getBean(PersonDAO.class);
System.out.println("=================save3()==================");
// 增加一条数据
Person person = new Person();
person.setName("Pankaj");
person.setCountry("India");
personDAO.save3(person);
System.out.println("================listAll()===================");
// 检索所有数据
List<Person> list = personDAO.list();
for (Person p : list) {
System.out.println("所有记录:" + p);
}
System.out.println("================update3()===================");
// 更新一条Person记录
person.setCountry("zhongguo");
personDAO.update3(person);
System.out.println("更新一条记录India-->zhongguo:" + personDAO.findOne(person.getId()));
System.out.println("================delete()===================");
// 删除一条Person记录
personDAO.delete(person); context.close();
}
}

运行结果

=================save1()==================
================update1()===================
Hibernate: select person0_.id as id1_0_0_, person0_.country as country2_0_0_, person0_.name as name3_0_0_ from PERSON person0_ where person0_.id=?
更新一条记录India-->zhongguo:null =================save2()==================
================update2()===================
Hibernate: select person0_.id as id1_0_0_, person0_.country as country2_0_0_, person0_.name as name3_0_0_ from PERSON person0_ where person0_.id=?
更新一条记录India-->zhongguo:null =================save3()==================
Hibernate: insert into PERSON (country, name) values (?, ?)
================update3()===================
Hibernate: update PERSON set country=?, name=? where id=?
Hibernate: select person0_.id as id1_0_0_, person0_.country as country2_0_0_, person0_.name as name3_0_0_ from PERSON person0_ where person0_.id=?
更新一条记录India-->zhongguo:id=8, name=Pankaj, country=zhongguo

原因分析

一共有三个测试例子,第一个例子test1()方法,调用save1()方法,使用spring aop配置的事务,从输出结果可以看出,数据没有插入数据库。update1()方法与save1()方法是相同情况。

第二个例子test2()方法,调用save2()方法,persist()方法被包围在spring aop配置的事务和session2的事务中(事务有提交),从输出结果可以看出,数据没有插入数据库。update2()方法与save2()方法是相同情况。

第三个例子test3()方法,persist()方法被包围在spring aop配置的事务和session1的事务中(事务有提交),从输出结果可以看出,数据成功插入数据库。update3()方法与save3()方法是相同情况。

通过实例程序可以看出,persist(),以及update()方法需要在调用它们的session中的事务中执行,最后该session的事务需要commit。

源代码可以从github获取:https://github.com/xiaoheike/SpringHibernateWithTransactionExample,这份源代码是spring + hibernate + spring aop 配置事务的demo工程。在完成demo过程中发现该问题,一直无法理解,一周之后恍然大悟,遂写这篇博客。

教程结束,感谢阅读。

欢迎转载,但请注明本文链接,谢谢。

2016/4/15 18:38:01

hibernate persist update 方法没有正常工作(不保存数据,不更新数据)的更多相关文章

  1. hibernate的update() 更新延迟或者无法更新,导致同个service调用存储过程执行方法不精确

    hibernate的update()方法无法更新,不报错 原因是hibernate的update方法操作的是缓存,可以flush下先. 设置缓存为false理论上也可. 在一个serivce方法里,执 ...

  2. Hibernate的注解方法的使用

    1.配置映射关系的xml方式 我们知道,Hibernate是一个典型的ORM框架,用以解决对象和关系的不匹配.其思想就是将关系数据库中表的记录映射成为对象,以对象形式展现,这样一来,就可以把对数据库的 ...

  3. [原创]java WEB学习笔记79:Hibernate学习之路--- 四种对象的状态,session核心方法:save()方法,persist()方法,get() 和 load() 方法,update()方法,saveOrUpdate() 方法,merge() 方法,delete() 方法,evict(),hibernate 调用存储过程,hibernate 与 触发器协同工作

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  4. Hibernate各保存方法之间的差 (save,persist,update,saveOrUpdte,merge,flush,lock)等一下

    hibernate保存  hibernate要保存的目的是提供一个方法,多.它们之间有许多不同之处,点击此处详细说明.使得差: 一.预赛: 在所有.阐释.供hibernate,,transient.p ...

  5. hibernate的各种保存方式的区别 (save,persist,update,saveOrUpdte,merge,flush,lock)等

    hibernate的保存hibernate对于对象的保存提供了太多的方法,他们之间有很多不同,这里细说一下,以便区别:一.预备知识:在所有之前,说明一下,对于hibernate,它的对象有三种状态,t ...

  6. hibernate的各种保存方式的区别 (save,persist,update,saveOrUpdte,merge,flush,lock)

    hibernate的保存hibernate对于对象的保存提供了太多的方法,他们之间有很多不同,这里细说一下,以便区别:一.预备知识:在所有之前,说明一下,对于hibernate,它的对象有三种状态,t ...

  7. hibernate中保存一个对象后再设置此对象的属性为什么不需要调用update方法了

    hibernate中保存一个对象后再设置此对象的属性为什么不需要调用update方法了 例如session.save(user);user.setAge(20); 原因: hibernate对象的三种 ...

  8. Hibernate HQL的update方法详解

    虽然hibernate提供了许多方法对数据库进行更新,但是这的确不能满足开发需要.现在讲解一下用hql语句对数据进行更新. 不使用参数绑定格式String hql="update User ...

  9. Hibernate的hql语句save,update方法不执行

    Hibernate的hql语句save,update方法不执行 可能出现的原因问题: 未进行事务管理 需要进行xml事务配置或者注解方式的事务配置

随机推荐

  1. AJAX格式

    var xmlHttp;function getXmlHttp(){ if(window.ActiveXObject){ xmlHttp = new ActiveXObject("MICRO ...

  2. Virtual Box 下Ubuntu桥接网络设置

    转自:http://os.51cto.com/art/200908/144564.htm 一般而言,安装完VirtualBox设定网路时选择默认的NAT模式,Guest就可顺利联网了,但是这种方式比较 ...

  3. 一次DB服务器性能低下引发的对Nonpaged Pool Leak问题的诊断

    1. 问题表象+分析 最开始是DB访问性能下降,某个不用Cache.直接到DB的查询10s+都不返回.上去一看,DB Server内存97%,可用内存才100多M. Windows毕竟不是iOS,不留 ...

  4. Websocket 协议解析

    WebSocket protocol 是HTML5一种新的协议.它是实现了浏览器与服务器全双工通信(full-duplex).          现 很多网站为了实现即时通讯,所用的技术都是轮询(po ...

  5. 在Django中进行注册用户的邮件确认

    之前利用Flask写博客时(http://hbnnlove.sinaapp.com),我对注册模块的逻辑设计很简单,就是用户填写注册表单,然后提交,数据库会更新User表中的数据,字段主要有用户名,哈 ...

  6. [Linux-脚本]排序、统计、合并命令

    1.排序命令 - sort: sort可以帮我们进行排序,排序顺序按照LANG(语系环境变量)确定.据观察,sort排序以行为单位进行.排序以第一个不相同的字符决定先后顺序(只与第一个不相同的字符相关 ...

  7. 数据存储之CoreData

    #import "ViewController.h" #import <CoreData/CoreData.h> #import "Person.h" ...

  8. 2014年6月份第3周51Aspx源码发布详情

      基于知识树的多课程网络教学平台源码  2014-6-16 [VS2008]功能介绍:本平台是一个支持网上教学的网站,支持多个课程,教师可根据需要创建课程,进行课程结构.题库等的管理.   技术特色 ...

  9. php生成html文件的多种方法介绍

    我经常会在网上看到有人问怎么将整个动态的网站静态化,其实实现的方法很简单.  代码如下 复制代码 <?php//在你的开始处加入 ob_start(); ob_start(); //以下是你的代 ...

  10. 在oracle中通过connect by prior来实现递归查询!

    注明:该文章为引用别人的文章,链接为:http://blog.csdn.net/apicescn/article/details/1510922 ,本人记录下来只是为了方便查看 原文: connect ...