1.概述, 事务管理, 编程式和说明式事务管理

2. 事务属性

传播行为:

传播行为

意义

PROPAGATION_MANDATORY

该方法必须运行在一个事务中。如果当前事务不存在,将抛出一个异常。

PROPAGATION_NESTED

若当前已经存在一个事务,则该方法应当运行在一个嵌套的事务中。被嵌套的事务可以从当前事务中单独的提交或回滚。若当前事务不存在,则看起来就和PROPAGATION_REQUIRED没有两样。

PROPAGATION_NEVER

当前的方法不应该运行在一个事务上下文中。如果当前存在一个事务,则会抛出一个异常。

PROPAGATION_NOT_SUPPORTED

表示该方法不应在事务中运行。如果一个现有的事务正在运行,他将在该方法的运行期间被挂起。如果使用jta的事务管理器,需要访问jtatansactionmanager.

传播行为

意义

PROPAGATION_REQUIRED

表示当前方法必须运行在一个事务中。若一个现有的事务正在进行中,该方法将会运行在这个事务中。否则的话,就要开一个新的事务。

PROPAGATION_REQUIRES_NEW

表示当前方法必须运行在它自己的事务里。他将启动一个新的事务。如果一个现有事务在运行的话,将在这个方法运行期间被挂起。若使用jtaTransactionManager,则需要访问transactionManager

PROPAGATION_SUPPORTS

当前方法不需要事务处理环境,但如果有一个事务已经在运行的话,这个方法也可以在这个事务里运行。

隔离级别

隔离级别

含义

ISOlATION_DEFAULT

使用后端数据库默认的隔离级别

ISOLATION_READ_UNCOMMITED

允许你读取还未提交后数据。可能导致脏、幻、不可重服

ISOLATION_READ_COMMITTED

允许在并发事务已经提交后读取。可防止脏读,但幻读和 不可重复读仍可发生。

ISOLATION_REPEATABLE_READ

对相同字段的多次读取是一致的,除非数据被事务本身改变。可防止脏、不可重复读,幻读仍可能发生。

ISOLATION_SERIALABLE

完全服从ACID的隔离级别,确保不发生脏、幻、不可重复读。这在所有的隔离级别中是最慢的,它是典型的通过完全锁定在事务中涉及的数据表来完成的。

只读

若对数据库只进行读操作,可设置事务只读的属性,使用某些优化措施。数据库会进行优化处理。若使用hibernate作为持久化机制,声明一个只读事务会使hibernate的flush模式设置为FLUSH_NEVER。避免不必要的数据同步,将所有更新延迟到事务的结束。

事务超时

若事务在长时间的运行,会不必要的占用数据库资源。设置超时后,会在指定的时间片回滚。将那些具有可能启动新事务的传播行为的方法的事务设置超时才有意义(PROPAGATION_REQUIRED,PROPAGATION_REQUIRES_NEW,PROPAGATION_NESTED)。

回滚规则

3. 示例代码

Customer.java, javabean 对象

public class Customer {private Integer id ;private String name ;private Integer age ;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 Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}

Customer.hbm.xml ,映射配置文件

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping><class name="cn.itcast.spring.domain.Customer" table="customers" lazy="false"><id name="id" column="id" type="integer"><generator class="identity" /></id><property name="name" column="name" type="string" not-null="true"/><property name="age" column="age" type="integer" /></class>
</hibernate-mapping>

CustomerDao.java, dao层接口

public interface CustomerDao {public void insertCustomer(Customer c);public void updateCustomer(Customer c);public List<Customer> findCustomerByName(String name);//批量保存//public void saveCustomers(List<Customer> list);
}

CustomerDaoImpl.java,dao接口 模板实现

/*** CustomerDaoImpl*/
public class CustomerDaoImpl implements CustomerDao {//hibernate模板,封装样板代码private HibernateTemplate ht ;public void setHt(HibernateTemplate ht) {this.ht = ht;}public List<Customer> findCustomerByName(String name) {String hql = "from Customer c where c.name = ?";return ht.find(hql, name);}public void insertCustomer(Customer c) {ht.save(c);}public void updateCustomer(Customer c) {ht.update(c);}/*** 批量保存*/
//  public void saveCustomers(final List<Customer> list) {
//      ht.execute(new HibernateCallback(){
//          public Object doInHibernate(Session session)
//                  throws HibernateException, SQLException {
//              Transaction tx = null;
//              try {
//                  tx = session.beginTransaction();
//                  for(Customer c : list){
//                      session.save(c);
//                  }
//                  tx.commit();
//              } catch (Exception e) {
//                  tx.rollback();
//                  e.printStackTrace();
//              }
//              return null;
//          }});
//  }
}

CustomerDaoSupportImpl.java , dao接口 HibernateDaoSupport 实现

/*** CustomerDaoImpl*/
public class CustomerDaoSupportImpl extends HibernateDaoSupport implements CustomerDao {public List<Customer> findCustomerByName(String name) {String hql = "from Customer c where c.name = ?";return getHibernateTemplate().find(hql, name);}public void insertCustomer(Customer c) {getHibernateTemplate().save(c);}public void updateCustomer(Customer c) {getHibernateTemplate().update(c);}public void saveCustomers(List<Customer> list) {// TODO Auto-generated method stub}
}

CustomerService.java,service层接口

public interface CustomerService {public void insertCustomer(Customer c);public void updateCustomer(Customer c);public List<Customer> findCustomerByName(String name);//批量保存public void saveCustomers(List<Customer> list);
}

CustomerServiceImpl.java, service层接口实现, 编程式事务管理

public class CustomerServiceImpl implements CustomerService {//daoprivate CustomerDao dao ;//事务模板,封装事务管理的样板代码private TransactionTemplate tt ;//注入事务模板public void setTt(TransactionTemplate tt) {this.tt = tt;}//注入daopublic void setDao(CustomerDao dao) {this.dao = dao;}public List<Customer> findCustomerByName(String name) {return dao.findCustomerByName(name);}public void insertCustomer(Customer c) {dao.insertCustomer(c);}/*** 批量保存, 编程式事务管理*/public void saveCustomers(final List<Customer> list) {
//      for(Customer c : list){
//          dao.insertCustomer(c);
//      }tt.execute(new TransactionCallback(){public Object doInTransaction(TransactionStatus status) {try {for(Customer c : list){dao.insertCustomer(c);}} catch (RuntimeException e) {e.printStackTrace();//设置回滚status.setRollbackOnly();}return null;}});}public void updateCustomer(Customer c) {dao.updateCustomer(c);}
}

CustomerServiceDeclareImpl.java , service层接口实现, 声明式事务管理

/*** 声明式事务管理,通过aop框架实现*/
public class CustomerServiceDeclareImpl implements CustomerService {//daoprivate CustomerDao dao ;//注入daopublic void setDao(CustomerDao dao) {this.dao = dao;}public List<Customer> findCustomerByName(String name) {return dao.findCustomerByName(name);}public void insertCustomer(Customer c) {dao.insertCustomer(c);}/*** 批量保存, 编程式事务管理*/public void saveCustomers(final List<Customer> list) {for(Customer c : list){dao.insertCustomer(c);}}public void updateCustomer(Customer c) {dao.updateCustomer(c);}
}

jdbc.properties, 数据库配置信息

jdbc.driverclass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=rootc3p0.pool.size.max=10
c3p0.pool.size.min=2
c3p0.pool.size.ini=3
c3p0.pool.size.increment=2hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=none

sh.xml, spring配置文件,编程式

<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd "><!-- 指定分散配置的文件的位置 --><context:property-placeholder location="classpath:cn/itcast/spring/hibernate/jdbc.properties"/><!-- 配置c3p0数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driverclass}" /><property name="jdbcUrl" value="${jdbc.url}" /><property name="user" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="maxPoolSize" value="${c3p0.pool.size.max}" /><property name="minPoolSize" value="${c3p0.pool.size.min}" /><property name="initialPoolSize" value="${c3p0.pool.size.ini}" /><property name="acquireIncrement" value="${c3p0.pool.size.increment}" /></bean><!-- 本地回话工厂bean,spring整合hibernate的核心入口 --><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource" /><!-- 指定hibernate自身的属性 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">${hibernate.dialect}</prop><prop key="hibernate.show_sql">${hibernate.show_sql}</prop><prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop></props></property><!-- 方式一:映射资源文件的位置<property name="mappingResources"><list><value>classpath:cn/itcast/spring/domain/Customer.hbm.xml</value></list></property>--><!--方式二--><property name="mappingDirectoryLocations"><list><value>classpath:cn/itcast/spring/domain</value></list></property><!--方式二:使用hibernate自身的配置文件配置<property name="configLocations"><list><value>classpath:hibernate.cfg.xml</value></list></property>--></bean><!-- hibernate模板,封装样板代码 --><bean id="ht" class="org.springframework.orm.hibernate3.HibernateTemplate"><property name="sessionFactory" ref="sessionFactory" /></bean><!-- customerDao --><bean id="customerDao" class="cn.itcast.spring.hibernate.CustomerDaoImpl"><property name="ht" ref="ht" /></bean><!-- hibernate事务管理器,在service层面上实现事务管理,而且达到平台无关性 --><bean id="htm" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean><!-- 事务模板,封装了事务管理的样板代码 --><bean id="tt" class="org.springframework.transaction.support.TransactionTemplate"><property name="transactionManager" ref="htm" /></bean><!-- customerService --><bean id="customerService" class="cn.itcast.spring.hibernate.CustomerServiceImpl"><property name="dao" ref="customerDao" /><property name="tt" ref="tt" /></bean><!-- ************************ daoSupport ******************** --><bean id="customerDaoSupport" class="cn.itcast.spring.hibernate.CustomerDaoSupportImpl"><property name="sessionFactory" ref="sessionFactory" /></bean>
</beans>

shDeclare.xml, spring配置文件,声明式

<?xml version="1.0"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd "><!-- 指定分散配置的文件的位置 --><context:property-placeholder location="classpath:cn/itcast/spring/hibernate/jdbc.properties"/><!-- 配置c3p0数据源 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driverclass}" /><property name="jdbcUrl" value="${jdbc.url}" /><property name="user" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><property name="maxPoolSize" value="${c3p0.pool.size.max}" /><property name="minPoolSize" value="${c3p0.pool.size.min}" /><property name="initialPoolSize" value="${c3p0.pool.size.ini}" /><property name="acquireIncrement" value="${c3p0.pool.size.increment}" /></bean><!-- 本地回话工厂bean,spring整合hibernate的核心入口 --><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="dataSource" ref="dataSource" /><!-- 指定hibernate自身的属性 --><property name="hibernateProperties"><props><prop key="hibernate.dialect">${hibernate.dialect}</prop><prop key="hibernate.show_sql">${hibernate.show_sql}</prop><prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop></props></property><!-- 映射资源文件的位置<property name="mappingResources"><list><value>classpath:cn/itcast/spring/domain/Customer.hbm.xml</value></list></property>--><property name="mappingDirectoryLocations"><list><value>classpath:cn/itcast/spring/domain</value></list></property><!-- 使用hibernate自身的配置文件配置<property name="configLocations"><list><value>classpath:hibernate.cfg.xml</value></list></property>--></bean><!-- hibernate模板,封装样板代码 --><bean id="ht" class="org.springframework.orm.hibernate3.HibernateTemplate"><property name="sessionFactory" ref="sessionFactory" /></bean><!-- customerDao --><bean id="customerDao" class="cn.itcast.spring.hibernate.CustomerDaoImpl"><property name="ht" ref="ht" /></bean><!-- hibernate事务管理器,在service层面上实现事务管理,而且达到平台无关性 --><bean id="htm" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory" /></bean><!-- customerService,目标对象 --><bean id="customerServiceTarget" class="cn.itcast.spring.hibernate.CustomerServiceDeclareImpl"><property name="dao" ref="customerDao" /></bean><!-- 代理对象 --><bean id="customerService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"><!-- 注入事务管理器 --><property name="transactionManager" ref="htm" /><property name="proxyInterfaces"><list><value>cn.itcast.spring.hibernate.CustomerService</value></list></property><property name="target" ref="customerServiceTarget" /><!-- 事务属性集(设置事务策略的), 事务属性:传播行为,隔离级别,只读,超时,回滚规则 --><property name="transactionAttributes"><props><prop key="save*">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop><prop key="update*">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop><prop key="delete*">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop><prop key="insert*">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop><!--对数据库只进行读操作,可设置事务只读的属性,使用某些优化措施。数据库会进行优化处理。--><prop key="load*">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop><prop key="get*">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop><prop key="find*">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop><prop key="*">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop></props></property></bean>
</beans>

AppService.java 测试代码1

public class AppService {public static void main(String[] args) throws SQLException {ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/spring/hibernate/sh.xml");CustomerService cs = (CustomerService) ac.getBean("customerService");List<Customer> list = new ArrayList<Customer>();Customer c = null ;for(int i = 0 ; i < 10 ; i++){c = new Customer();if(i == 9){c.setName(null);}else{c.setName("tom" + i);}c.setAge(20 + i);list.add(c);}cs.saveCustomers(list);}}

AppServiceDeclare.java 测试代码二

public class AppServiceDeclare {public static void main(String[] args) throws SQLException {ApplicationContext ac = new ClassPathXmlApplicationContext("cn/itcast/spring/hibernate/shDeclare.xml");CustomerService cs = (CustomerService) ac.getBean("customerService");List<Customer> list = new ArrayList<Customer>();Customer c = null ;for(int i = 0 ; i < 10 ; i++){c = new Customer();if(i == 9){c.setName(null);}else{c.setName("tom" + i);}c.setAge(20 + i);list.add(c);}cs.saveCustomers(list);}}

转载于:https://www.cnblogs.com/xj626852095/p/3648141.html

Spring -- spring 和 hibernate 整合相关推荐

  1. java spring hiberate_Spring+SpringMVC+Hibernate整合实例讲解

    使用Maven构建项目,用pom.xml引入相应jar,配置以下文件 创建spring.xml: xmlns="http://www.springframework.org/schema/b ...

  2. Spring+Hibernate整合

    因为整合spring和hibernate所以,需要用到spring里面复写Hibernate的类以有DI和IOC特性 db.sql hibernate_basic数据库 表 person 字段 pid ...

  3. Struts+Spring+Hibernate整合入门详解

    标签: strutshibernatespringbeanactionimport 2007-08-12 16:05 36280人阅读 评论(13) 收藏 举报 分类: STRUTS&SPRI ...

  4. spring入门(11)-spring与hibernate整合完成增删改查的操作(封装HibernateTemplate模版类对象)

    今天是spring的最后一节课,这节课老师讲了spring与hibernate整合完成增删改查的操作,这是很重要的一节课,这也是第一次真正的实现spring结合Hibernate和数据库连接上,下面是 ...

  5. Java程序员从笨鸟到菜鸟之(七十九)细谈Spring(八)spring+hibernate整合基本详解

    由于spring和hibernate处于不同的层次,Spring关心的是业务逻辑之间的组合关系,Spring提供了对他们的强大的管理能力, 而Hibernate完成了OR的映射,使开发人员不用再去关心 ...

  6. spring和hibernate整合的几种方式详细介绍

    Spring与Hibernate整合 Spring与Hibernate整合关键点: 1) Hibernate的SessionFactory对象交给Spring创建: 2) hibernate事务交给s ...

  7. mysql5.7 hibenate5.1_5.7 Spring与Hibernate整合应用

    下面以一个简单的实例说明Spring与Hibernate的整合策略,步骤如下. 1 在SQL Server 2005中创建数据库表 数据库名为XSCJ,表见附录A的登录表. 2 创建Web项目 命名为 ...

  8. Spring与Hibernate整合中,使用OpenSessionInViewFilter后出现sessionFactory未注入问题

    近期在知乎看到一句话,保持学习的有一种是你看到了很多其它的牛人,不甘心,真的不甘心. Spring和hibernate整合的时候,jsp页面做展现,发现展现属性出现: org.apache.jaspe ...

  9. Spring Spring MVC Hibernate 整合备忘

    以下为此三种框架整合配置的详细备注,以及部分问题备忘 项目结构和配置文件可访问 Github 查看 1. pom.xml 尽量使用 Maven 管理项目依赖以减少包引入时的麻烦,以及避免跨开发工具问题 ...

  10. 整合Spring框架和Hibernate框架

    -------------------siwuxie095 整合 Spring 框架和 Hibernate 框架 1.导入相关 jar 包(共 28 个) (1)导入 Spring 的核心 jar 包 ...

最新文章

  1. ROS系统 用Python或C++实现发布者Publisher
  2. Luogu P4708 画画 (Burnside引理、组合计数)
  3. [BUUCTF-pwn]——others_shellcode
  4. python操作redis用法详解
  5. JMetro版本11.6.5和8.6.5发布
  6. 微服务教程--什么是 Nacos
  7. 数据化风控中的核心指标与报表汇总
  8. 鼠标右键中没有新建选项,解决方法!
  9. 三诺 n20g 微型计算机,入门级音箱再现经典 三诺N-20GIII评测
  10. matlab凑数求和,凑数求和算法 C语言问题 C语言求和算法
  11. c语言编程入门教程+网易,人话讲编程·C语言入门:第一讲,Hello World
  12. 计算机 90学时培训总结,90学时培训心得体会
  13. qiao-get-ip:免费获取公网ip
  14. 高手和普通人的区别,就在破局思维
  15. r语言 读服务器数据,R语言数据实战 | 安装R语言
  16. 编辑合成图片怎么做?手把手教你合成
  17. python中使用linux命令
  18. linux编译怎么选择cpu,使用cpuminer在Linux系统中用CPU挖矿
  19. VMware Workstation pro无法在Windows上运行,检查可在Windows上运行的此应用的更新版本
  20. 爱奇艺要怎么样才能更换视频解码设置

热门文章

  1. linux的memmap函数_究竟有多少linux内核命令行参数
  2. php查询sql语句错误,Thinkphp3.2.3在SQL执行错误时查看SQL语句
  3. [python]一个遍历多层文件夹,然后替换文件内容和目录名称的案例
  4. 用 Access+Outlook 来采集信息
  5. 「镁客·请讲」Site24×7李飞:云服务是大势所趋,云监控生意又要怎么做?...
  6. SQL中关于where后面不能放聚合函数(如sum等)的解决办法
  7. Windows命令查看文件MD5
  8. zabbix+telegram 报警
  9. 3.Knockout.Js(属性绑定)
  10. ×××背景知识技术介绍