Java事务管理学习之Spring和Hibernate详解
作者:oscar999 发布时间:2023-04-11 00:01:25
环境与版本
本文出来之前的一篇文章中的hibernate的相关lib 外
Java事务管理之Hibernate
还需要加入spring的lib 包和如下的一些依赖包
org.aopalliance
org.aspectj
org.apache.commons
Spring 的版本是Spring 4.1.5。
依赖包也可以到Spring 官方网站下载到 ,名字类似 spring-framework-3.0.2.RELEASE-dependencies
理论知识
Spring和Hibernate整合后,通过Hibernate API进行数据库操作时发现每次都要opensession,close,beginTransaction,commit,这些都是重复的工作,我们可以把事务管理部分交给spring框架完成。
使用spring管理事务后在dao中不再需要调用beginTransaction和commit,也不需要调用session.close()
,使用API sessionFactory.getCurrentSession()
来替代sessionFactory.openSession()
* 如果使用的是本地事务(jdbc事务)
<property name="hibernate.current_session_context_class">thread</property>
* 如果使用的是全局事务(jta事务)
<property name="hibernate.current_session_context_class">jta</property>
Spring中Propagation类的事务属性详解:
PROPAGATION_REQUIRED:支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
PROPAGATION_SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行。
PROPAGATION_MANDATORY:支持当前事务,如果当前没有事务,就抛出异常。
PROPAGATION_REQUIRES_NEW:新建事务,如果当前存在事务,把当前事务挂起。
PROPAGATION_NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER:以非事务方式执行,如果当前存在事务,则抛出异常。
PROPAGATION_NESTED:支持当前事务,如果当前事务存在,则执行一个嵌套事务,如果当前没有事务,就新建一个事务。
Spring 可以使用xml方式进行配置或是使用注解声明的方式进行事务的管理。
xml 方式配置事务代码实例
代码结构如下:
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<context:component-scan base-package="com.oscar999.trans.sprhib" />
<context:property-placeholder location="classpath:/com/oscar999/trans/sprhib/config.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!-- Connection Info -->
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>
<prop key="jdbc.use_streams_for_binary">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.oscar999.trans.sprhib.model</value>
</list>
</property>
</bean>
<!-- Transaction -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.oscar999.trans.sprhib.dao.ProductDAOImpl.*(..))" id="pointcut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
</aop:config>
</beans>
config.properties
jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@12.6.18.43:1521:orcl
jdbc.username=
jdbc.password=oracle
Product.Java
/**
* @Title: Product.java
* @Package com.oscar999.trans.hibernate
* @Description:
* @author XM
* @date Feb 15, 2017 1:44:47 PM
* @version V1.0
*/
package com.oscar999.trans.sprhib.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author XM
*
*/
@Entity
@Table(name = "TEST_PRODUCT")
public class Product implements Serializable {
public Product() {
}
@Id
@Column(name = "ID")
private Integer id;
@Column(name = "NAME")
private String name;
@Column(name = "PRICE")
private String price;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
ProductDAOImpl.java
/**
* @Title: ProductDAOImpl.java
* @Package com.oscar999.trans.sprhib
* @Description:
* @author XM
* @date Feb 15, 2017 4:15:09 PM
* @version V1.0
*/
package com.oscar999.trans.sprhib.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.oscar999.trans.sprhib.model.Product;
/**
* @author XM
*
*/
@Repository
public class ProductDAOImpl {
@Autowired
private SessionFactory sessionFactory;
public Product findProductById(int id) {
Session session = sessionFactory.getCurrentSession();
Product product = (Product) session.get(Product.class, id);
return product;
}
public Product saveProduct(Product product) {
Session session = sessionFactory.getCurrentSession();
session.save(product);
return product;
}
}
ProductServiceImpl.java
package com.oscar999.trans.sprhib;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.oscar999.trans.sprhib.dao.ProductDAOImpl;
import com.oscar999.trans.sprhib.model.Product;
@Service
public class ProductServiceImpl {
@Autowired
private ProductDAOImpl productdao;
public void findProduct(int id) {
Product product = productdao.findProductById(id);
if (product != null) {
System.out.println(product.getName());
}
}
public void saveProduct() {
Product product = new Product();
product.setId(2);
product.setName("product2");
product.setPrice("price2");
productdao.saveProduct(product);
}
}
TestMain.java
/**
* @Title: TestMain.java
* @Package com.oscar999.trans.sprhib
* @Description:
* @author XM
* @date Feb 15, 2017 3:54:54 PM
* @version V1.0
*/
package com.oscar999.trans.sprhib;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author XM
*
*/
public class TestMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("com/oscar999/trans/sprhib/applicationContext.xml");
ProductServiceImpl productService = applicationContext.getBean(ProductServiceImpl.class);
//productService.findProduct(1);
productService.saveProduct();
}
}
说明如下:
get 可以不需要transaction
插入或是更新如果没有的话, 就不会更新成功
声明方式配置事务
需要在xml配制中设置<tx:annotation-driven transaction-manager="transactionManager">
事物注解方式: @Transactional
当标于类前时,标示类中所有方法都进行事物处理,以下代码在service层进行事务处理(给Service层配置事务是比较好的方式,因为一个Service层方法操作可以关联到多个DAO的操作。在Service层执行这些Dao操作,多DAO操作有失败全部回滚,成功则全部提交。)
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public User getUserById(int id) {
return userDao.findUserById(id);
}
}
当类中某些方法不需要事物时:
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public User getUserById(int id) {
return userDao.findUserById(id);
}
来源:http://blog.csdn.net/oscar999/article/details/55261446


猜你喜欢
- Spring5路径匹配器PathPatternPathPattern 对url地址匹配的处理更加快速,它和AntPathMatcher 主要
- 之前已经为大家介绍过利用Java实现带GUI的气泡诗词特效,本文将为大家介绍另一种方法同样也可以实现气泡诗词的效果。下面是示例代码impor
- 前言传统的Restful API 存在诸多的问题,首先它无法控制返回的字段,前端也无法预判后端的返回结果,另外不同的返回结果对应不同的请求地
- 图库在播放幻灯片时,按power键灭屏,然后再亮屏,会发现幻灯片继续在播放,没有显示keyguard。如何在亮屏后显示解锁界面。 修改方法是
- 引言本文我们来分析NameServer相关代码,在正式分析源码前,我们先来回忆下NameServer的功能:NameServer是一个非常简
- analyzer的使用规则查询只能查找倒排索引表中真实存在的项, 所以保证文档在索引时与查询字符串在搜索时应用相同的分析过程非常重要,这样查
- java实现字符串匹配暴力匹配/** * 暴力匹配 * * @param str1 需要找的总字符串 * @param str2 需要找到的
- 前言quarkus号称超音速亚原子JAVA为Graalvm量身定制的java堆栈,是否名副其实呢?下面就来看看真实情况如何。动手前先简单介绍
- 文章描述可能我标题描述不太准确,所以还是要稍微解释下:横线样式就是将TextBox以一条底横线的形式展示在页面,占位提示就是Web的Plac
- Json格式在后台服务中的重要性就不多说了,直入正题。首先引入pom文件,这里使用的是1.2.83版本<dependency>
- 一. MediaPlayer 状态机 介绍Android MediaPlayer 状态即图例 :1. Idle (闲置) 状态 和 End
- Lambda用到了JDK8自带的一个函数式接口Comparator<T>。准备一个Apple类public class Appl
- 本文实例讲述了Java数组高级算法与Arrays类常见操作。分享给大家供大家参考,具体如下:冒泡排序冒泡排序原理冒泡排序代码:package
- 程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。#include <s
- 方法一、利用控件或窗体的Paint事件中的PainEventArgs在窗体或控件的Paint事件中接收对图形对象的引用,作为PaintEve
- 一、文件上传概述实现Web开发中的文件上传功能,需要两步操作:1、在Web页面中添加上传输入项 <form
- 说起空间动态、微博的点赞效果,网上也是很泛滥,各种实现与效果一大堆。而详细实现的部分,讲述的也是参差不齐,另一方面估计也有很多大侠也不屑一顾
- 前言Dijkstra算法是最短路径算法中为人熟知的一种,是单起点全路径算法。该算法被称为是“贪心算法”的成功典范。本文接下来将尝试以最通俗的
- 在javaweb中写了一个图片的链接,可以打开预览,另外提供一个下载功能。以下是预览代码,没什么好说的;href若连接的是一个压缩包文件之类
- 简介在多线程中解决线程安全的问题时常用到Synchronized,现在的synchronized相对于早期的synchronized做出了优