Spring的transaction-manager的用法
2)transaction-manager:
例 2.2.2
注意配置文件头加了两条:spring-tx-3.0.xsd和xmlns:tx
<?xml version="1.0" encoding="UTF-8"?>
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
>
package service;
import java.sql.Types;
import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import com.NiutDAO;
import service.interfac.ILoginService;
public class LoginServiceImpl implements ILoginService {
@Resource
private JdbcTemplate jt;
NiutDAO niutDAO;
public void setNiutDAO(NiutDAO niutDAO) {
this.niutDAO = niutDAO;
}
public void login() {
updateRegister(15,1);
System.out.println("successfully update 1");
updateRegisterWrong(19,2);
System.out.println("successfully update 2");
}
public void updateRegister(int age,int id) {
String sql = "UPDATE register SET age=? WHERE id=?";
Object params[] = new Object[] { new Integer(age),
new Integer(id) };
int type[] = new int[] { Types.INTEGER , Types.INTEGER };
jt.update(sql, params, type);
}
public void updateRegisterWrong(int age,int id) {
String sql = "UPDATE register SET age=? WWWWWWW id=?";
Object params[] = new Object[] { new Integer(age),
new Integer(id) };
int type[] = new int[] { Types.INTEGER , Types.INTEGER };
jt.update(sql, params, type);
}
}
即使updateRegister(15,1);成功执行,但数据库中结果并没有被更新,因为updateRegisterWrong(19,2);的错误致使updateRegister(15,1);的结果发生了回滚。
输出结果:
successfully update 1
严重: Servlet.service() for servlet spring threw exception
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WWWWWWW id=2' at line 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2921)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1570)
更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44591615/article/details/109206425