Spring入门Blog[十二、Spring中Annotation声明事务]

2014-11-24 08:29:24 · 作者: · 浏览: 0

Spring的声明式事务Annotation的实现------AOP应用

首先先讨论一个问题:

事务放在service层还是放在dao层呢

Dao层只是针对于某一个实体进行CRUD的操作。如果在增加删除一个表的时候。比如USER我们要在LOG表中记录相应的日志。那么在DAO层如何完成。所以说Service层可能操作多个实体类。所以事务加载service层比较合适。因为不论我们保存哪一个实例出现了错误我们都可以回滚。而不是Log插入了,User没插入。反之亦然,这都是我们不愿意看到的。

下面举例Spring中事务通过Annotation方式是如何实现的:

1、 加入tx开头的命名空间并且配置事务manager和driven。代码如下:

[html]
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">












class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

classpath:jdbc.properties



class="org.apache.commons.dbcp.BasicDataSource">











com/spring/model/user.hbm.xml
com/spring/model/userlog.hbm.xml




hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create












2、在Java文件上使用注解标签:
[java]
//在Service层加入事务的控制。具体逻辑不在给予。
//在下面方法前面加逻辑
/*事务的传播性。如果当前执行环境中有事务,那么则会一直在
* 传播环境中传播下去。如果没有事务那么则会创建一个事务
*/
@Transactional(propagation=Propagation.REQUIRED)
public void save(User u){
u.setName("zhanglong");
UserLog log = new UserLog();
log.setMsg("user added");
userDaoImpl.save(u);
userLogDaoImpl.save(log);
}
作者:zhang6622056