Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >hibernate persist update 方法没有正常工作(不保存数据,不更新数据)

hibernate persist update 方法没有正常工作(不保存数据,不更新数据)

作者头像
用户3148308
发布于 2018-09-13 06:41:25
发布于 2018-09-13 06:41:25
2.4K01
代码可运行
举报
文章被收录于专栏:xiaoheikexiaoheike
运行总次数:1
代码可运行

工程结构

问题描述

在工程中通过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)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?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(实现方法)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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();
    }
}

测试类

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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();
    }
}

运行结果

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
=================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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-04-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Hibernate与Sping框架的整合
在resources目录下创建一个applicationContext.xml的配置文件
害恶细君
2022/11/22
8280
springmvc、spring、hibernate整合示例
在mysql数据库中建立一个user表,已对user的增删改查为例,整合springmvc、spring、hibernate。 1.web.xml中的配置:①spring监听器;②spring mvc的servlet;③字符编码过滤器。 <!-- spring 监听器的配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <c
yawn
2018/03/14
1.2K0
SSH框架完全整合 整合Spring和Hibernate:Spring整合Struts2
大三学期渐末,事情也挺多的,上周就开始着手整合SSH框架,到现在才真正的完成,过程中碰到了许多小问题(小问题大折腾,哭脸.jpg)。本着善始善终的原则,最终把它给完成了。 本篇文章就在: win7
MindMrWang
2018/04/16
2.5K0
SSH框架完全整合	整合Spring和Hibernate:Spring整合Struts2
Hibernate【缓存】知识要点
对象状态 Hibernate中对象的状态: 临时/瞬时状态 持久化状态 游离状态 学习Hibernate的对象状态是为了更清晰地知道Hibernate的设计思想,以及是一级缓存的基础…当然啦,也就一点
Java3y
2018/03/15
7500
Hibernate【缓存】知识要点
基于注解的Spring MVC整合Hibernate(所需jar包,spring和Hibernate整合配置,springMVC配置,重定向,批量删除)
大家好,又见面了,我是全栈君。 1、导入jar 2、web.xml配置 <?xml version=”1.0″ encoding=”UTF-8″?> <web-app version=”2.4″
全栈程序员站长
2022/07/10
8650
java之spring之spring整合hibernate
4.在src下,编写 hibernate.cfg.xml ,并且在cn.vincent.vo下编写vo类的映射文件 User.hbm.xml
Vincent-yuan
2019/09/11
7040
java之spring之spring整合hibernate
springmvc,spring,hibernate框架整合
spring系列的jar包 spring-webmvc(spring-aop spring-beans spring-context spring-core spring-expression spring-web) spring-jdbc spring-orm aspectjweaver aspectjrt aopalliance aop切面
微醺
2019/01/17
6520
SSH【史上最详细整合】
最详细搭建SSH框架环境 本博文主要是讲解如何搭建一个比较规范的SSH开发环境,以及对它测试【在前面的搭建中,只是整合了SSH框架,能够使用SSH实现功能】,而这次是相对规范的。 导入开发包 这里写图
Java3y
2018/03/16
1.2K0
SSH【史上最详细整合】
Hibernate【与Spring整合】
前言 前面已经学习了如何使用Spring与Struts2进行整合,本博文主要讲解如何使用Spring对Hibernate进行整合 Spring和Hibernate整合的关键点: SessionFactory对象交给Spring来创建 Hibernate的事务交给Spring进行管理 ---- Spring和Hibernate整合步骤 引入jar包 连接池/数据库驱动包 Hibernate相关jar Spring 核心包(5个) Spring aop 包(4个) spring-orm-3.2.5.RELEAS
Java3y
2018/03/15
7410
Hibernate【与Spring整合】
spring之整合Hibernate
这里需要说明的是table="SH_BOOK"中SH是表的前缀,我们在写hql语句时不用带上,系统会自动识别。
西西嘛呦
2020/08/26
4740
spring之整合Hibernate
Hibernate save, saveOrUpdate, persist, merge, update 区别
hibernate save()方法能够保存实体到数据库,正如方法名称save这个单词所表明的意思。我们能够在事务之外调用这个方法,这也是我不喜欢使用这个方法保存数据的原因。假如两个实体之间有关系(例如employee表和address表有一对一关系),如果在没有事务的情况下调用这个方法保存employee这个实体,除非调用flush()这个方法,否则仅仅employee实体会被保存。
用户3148308
2018/09/13
2.4K0
struts2+spring+hibernate整合步骤(1)
struts2、hibernate、spring所需jar包 struts-core-2.x.x.jar ----struts核心包 xwork-core-2.x.x.jar -----身体ruts在其撒很难过构建 ognl-2.6.x.jar ----对象导航语言 freemarker-2.3.x.jar ------struts2的ui标签的模板使用 commons-fileupload-1.2.x.jar ----文件上传组件 2.1.6版本后需加入此文件 str
Java帮帮
2018/03/15
7370
spring+hibernate+struts2+compass整合
http://www.cnblogs.com/hongten/gallery/image/113449.html
Hongten
2018/09/13
6760
hibernate笔记(一)
原始的jdbc操作, Connection/Statement/ResultSet
HUC思梦
2020/09/03
8390
SpringData【Spring整合Hibernate】
  在resources目录下创建spring的配置文件和数据库连接的属性文件,如下:
用户4919348
2019/05/19
6110
hibernate笔记加强版「建议收藏」
hibernate事实上就是ormapping框架,此框架的作用就是简单话数据库的操作。
全栈程序员站长
2022/07/10
1.1K0
Hibernate的四种查询方式(主键查询,HQL查询,Criteria查询,本地sql查询)和修改和添加
根据文章内容总结摘要。
别先生
2018/01/02
5.4K0
Hibernate的四种查询方式(主键查询,HQL查询,Criteria查询,本地sql查询)和修改和添加
Hibernate文件配置
映射需要通过XML的配置文件来完成,这个配置文件尽量统一(xxx.hbm.xml) Hibernate核心的配置:必须的配置、可选的配置、映射文件的引入
用户3112896
2019/09/26
4340
Hibernate文件配置
从事务角度粗窥架构的可扩展性和可维护性:内容整理自java web轻量级开发面试教程
    大家多少了解过架构,也听说过使用架构后,代码和可维护性和重用性能大大提升。这里我们来通过一些关于事务的实例,来感性地体会下架构带来的在可维护性方面的便利。本文来是从 java web轻量级开发面试教程从摘录的。 1 JDBC中的事务是方法层面的         ①通过setAutoCommit,设置非自动提交。在JDBC里,一般默认是自动提交,即有任何增删改的SQL语句都会当场执行。如果大家设置了非自动提交,记得在用好事务后设置回“自动提交”。     ②在合适的地方用connection.comm
用户1153489
2018/01/12
7260
SpringMVC+Hibernate4
 1) /SpringMVCHibernate4/src/main/webapp/view/index.jsp
py3study
2020/01/08
3620
相关推荐
Hibernate与Sping框架的整合
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验