spring作为低侵入的Java EE框架之一,能够很好地与其他框架进行整合,其中Spring与hibernate的整合实现的事务管理是常用的一种功能。 所谓事务,就必须具备ACID特性,即原子性、一致性、隔离性和持久性
注意@Transactional 注解及其支持类所提供的功能最低要求使用Java 5(Tiger)。
除了基于XML文件的声明式事务配置外,你也可以采用基于注解式的事务配置方法。直接在Java源代码中声明事务语义的做法让事务声明和将受其影响的代码距离更近了,而且一般来说不会有不恰当的耦合的风险,因为,使用事务性的代码几乎总是被部署在事务环境中。
下面的例子很好地演示了 @Transactional 注解的易用性,随后解释其中的细节。先看看其中的类定义:
- <!-- the service class that we want to make transactional -->
- @Transactional
- public class DefaultFooService implements FooService {
- Foo getFoo(String fooName);
- Foo getFoo(String fooName, String barName);
- void insertFoo(Foo foo);
- void updateFoo(Foo foo);
- }
当上述的POJO定义在Spring IoC容器里时,上述bean实例仅仅通过一 行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-2.0.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
-
-
- <bean id="fooService" class="x.y.service.DefaultFooService"/>
-
-
- <tx:annotation-driven transaction-manager="txManager"/>
-
-
- <