问题如题,方式试了很久就是不行,改成TransactionProxyFactoryBean方式就行,我把代码贴出来,请大家帮忙看看哪有问题。
applicationContext.xml<?xml version="1.0" encoding="UTF-8"?>
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.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.jdbc.datasource.DriverManagerDataSource">
value="com.mysql.jdbc.Driver" />
value="jdbc:mysql://localhost:3306/test" />
pointcut="execution(* transaction.ManagerImpl.*(..))" />
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
Dao接口FooDAO.java
package transaction;
public interface FooDAO{
String getFoo(String content);
void insertFoo(String foo);
void updateFoo(String foo,String newfoo);
}
Dao实现类FooDAOImpl.java
package transaction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
public class FooDAOImpl extends JdbcDaoSupport implements FooDAO {
public String getFoo(String content) {
JdbcTemplate jt=this.getJdbcTemplate();
String name = "";
name = (String) jt.queryForObject(
"SELECT content FROM test WHERE content = ?", new Object[] { content },
java.lang.String.class);
return name;
}
public void insertFoo(String foo){
JdbcTemplate jt=this.getJdbcTemplate();
jt.update("INSERT INTO test VALUES('"+foo+"')" );
}
//test2表在库里不存在,故意让它出错。
public void updateFoo(String foo,String newfoo) {
JdbcTemplate jt=this.getJdbcTemplate();
jt.update("update test2 set content ='"+newfoo+"' where content='"+foo+"'" );
}
}
业务类,也是事务管理的那个类ManagerImpl.java
public class ManagerImpl {
private static final Logger log = Logger.getLogger(ManagerImpl.class);
private FooDAO fooDAO;
public void setFooDAO(FooDAO fooDAO) {
this.fooDAO = fooDAO;
}
public void Test(){
String foo= "";
foo= fooDAO.getFoo("foo");
log.info(foo);
fooDAO.insertFoo("rree001");
foo= fooDAO.getFoo("rree001");
log.info(foo);
fooDAO.updateFoo("foo","test");
foo= fooDAO.getFoo("test");
log.info(foo);
}
}
测试类Boot.java
package transaction;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public final class Boot {
public static void main(final String[] args) throws Exception {
Resource resource = new FileSystemResource("src/applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
ManagerImpl managerImpl = (ManagerImpl) factory.getBean("managerImpl");
managerImpl.Test();
}
}
测试结果是insert成功,update失败但是事务没起作用,没有回滚,表里插入了记录。改成上面的Spring配置文件中注释的部分就能够回滚,表里没有插入记录。