Spring宣告式事務(AOP的tx方式)
阿新 • • 發佈:2019-02-08
類似於上一篇,這裡使用tx的方式來配置。
服務類StudentService.java程式碼如下:
package com.mysrc.service; import java.sql.Date; import java.util.List; import com.mysrc.dao.StudentDao; import com.mysrc.entity.Student; public class StudentService { private StudentDao dao; public void setDao(StudentDao dao) { this.dao = dao; } public void doComplexLogic() { // select List<Student> list = dao.getAllStudent(); for (Student student : list) { System.out.println(student); } // update Student student = list.get(0); student.setName("laohu.."); dao.updateStudent(student); System.out.println("did update temporarily..."); //int a = 9 / 0; // 遇到異常,整個事務回滾,也即上面的update不會成功 // 如果try catch捕獲這個異常,那整個事務會順利執行,不會回滾 int b = 2; if (b > 1) { throw new CustomRuntimeException(); // 事務不會回滾,也就是上面的update操作會提交 } // insert student = new Student(); student.setName("hello"); student.setBirth(new Date(354778)); student.setScore(78.9f); dao.addStudent(student); System.out.println("did insert..."); // delete dao.deleteStudent(3); System.out.println("did delete..."); } }
這裡doComplexLogic()方法上不再有註解修飾了。
Spring的應用程式上下文配置檔案applicationContext.xml的內容為:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx"> <bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mytestdb?characterEncoding=utf8" /> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="username" value="root" /> <property name="password" value="123456" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="30" /> <property name="maxWait" value="1000" /> <property name="validationQuery" value="select 1" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg name="dataSource" ref="basicDataSource"> </constructor-arg> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name="dataSource"> <ref bean="basicDataSource" /> </property> </bean> <bean id="studentDao" class="com.mysrc.dao.StudentDao"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate" /> </property> </bean> <bean id="studentService" class="com.mysrc.service.StudentService"> <property name="dao"> <ref bean="studentDao" /> </property> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="get*" propagation="NOT_SUPPORTED" read-only="true" /> <tx:method name="doComplexLogic" propagation="NESTED" isolation="REPEATABLE_READ" timeout="1000" rollback-for="java.lang.Exception" no-rollback-for="com.mysrc.service.CustomRuntimeException" /> </tx:attributes> </tx:advice> <!-- Spring AOP config --> <aop:config> <!-- 切入點 --> <aop:pointcut id="studentServicesPointcut" expression="execution(* com.mysrc.service.StudentService.*(..))" /> <!-- <aop:pointcut id="newServicesPointcut2" expression="execution(* com.model.*.*(..))" /> --> <aop:advisor advice-ref="txAdvice" pointcut-ref="studentServicesPointcut" /> <!-- <aop:advisor advice-ref="txAdvice" pointcut-ref="newServicesPointcut2" /> --> </aop:config> </beans>
順便介紹一下Spring中jdbcTemplate的用法例項
要使用Jdbctemplate 物件來完成jdbc 操作。通常情況下,有三種種方式得到JdbcTemplate 物件。
第一種方式:我們可以在自己定義的DAO 實現類中注入一個DataSource 引用來完 成JdbcTemplate 的例項化。也就是它是從外部“注入” DataSource 到DAO 中,然後 自己例項化JdbcTemplate,然後將DataSource 設定到JdbcTemplate 物件中。
第二種方式: 在 Spring 的 IoC 容器中配置一個 JdbcTemplate 的 bean,將 DataSource 注入進來,然後再把JdbcTemplate 注入到自定義DAO 中。
第三種方式: Spring 提供了 org.springframework.jdbc.core.support.JdbcDaoSupport 類 , 這 個 類 中 定 義 了 JdbcTemplate 屬性,也定義了DataSource 屬性,當設定DataSource 屬性的時候,會創 建jdbcTemplate 的例項,所以我們自己編寫的DAO 只需要繼承JdbcDaoSupport 類, 然後注入DataSource 即可。
/**
* 建立表
*/
public void create(String tableName){ //tb_test1
jdbcTemplate.execute("create table "+tableName +" (id integer,user_name varchar2(40),password varchar2(40))");
}
//jdbcTemplate.update適合於insert 、update和delete操作;
/**
* 第一個引數為執行sql
* 第二個引數為引數資料
*/
public void save3(User user) {
Assert.isNull(user, "user is not null");
jdbcTemplate.update("insert into tb_test1(name,password) values(?,?)",
new Object[]{user.getUsername(),user.getPassword()});
}
/**
* 第一個引數為執行sql
* 第二個引數為引數資料
* 第三個引數為引數型別
*/
@Override
public void save(User user) {
Assert.isNull(user, "user is not null");
jdbcTemplate.update(
"insert into tb_test1(name,password) values(?,?)",
new Object[]{user.getUsername(),user.getPassword()},
new int[]{java.sql.Types.VARCHAR,java.sql.Types.VARCHAR}
);
}
//避免sql注入
public void save2(final User user) {
Assert.isNull(user, "user is not null");
jdbcTemplate.update("insert into tb_test1(name,password) values(?,?)",
new PreparedStatementSetter(){
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
}
});
}
public void save4(User user) {
Assert.isNull(user, "user is not null");
jdbcTemplate.update("insert into tb_test1(name,password) values(?,?)",
new Object[]{user.getUsername(),user.getPassword()});
}
//返回插入的主鍵
public List save5(final User user) {
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement("insert into tb_test1(name,password) values(?,?)", new String[] {"id"});
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
return ps;
}
},
keyHolder);
return keyHolder.getKeyList();
}
@Override
public void update(final User user) {
jdbcTemplate.update(
"update tb_test1 set name=?,password=? where id = ?",
new PreparedStatementSetter(){
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.setInt(3, user.getId());
}
}
);
}
@Override
public void delete(User user) {
Assert.isNull(user, "user is not null");
jdbcTemplate.update(
"delete from tb_test1 where id = ?",
new Object[]{user.getId()},
new int[]{java.sql.Types.INTEGER});
}
@Deprecated //因為沒有查詢條件,所以用處不大
public int queryForInt1(){
return jdbcTemplate.queryForInt("select count(0) from tb_test1");
}
public int queryForInt2(User user){
return jdbcTemplate.queryForInt("select count(0) from tb_test1 where username = ?" ,
new Object[]{user.getUsername()});
}
//最全的引數3個
public int queryForInt3(User user){
return jdbcTemplate.queryForInt("select count(0) from tb_test1 where username = ?" ,
new Object[]{user.getUsername()},
new int[]{java.sql.Types.VARCHAR});
}
//可以返回是一個基本型別的值
@Deprecated //因為沒有查詢條件,所以用處不大
public String queryForObject1(User user) {
return (String) jdbcTemplate.queryForObject("select username from tb_test1 where id = 100",
String.class);
}
//可以返回值是一個物件
@Deprecated //因為沒有查詢條件,所以用處不大
public User queryForObject2(User user) {
return (User) jdbcTemplate.queryForObject("select * from tb_test1 where id = 100", User.class); //class是結果資料的java型別
}
@Deprecated //因為沒有查詢條件,所以用處不大
public User queryForObject3(User user) {
return (User) jdbcTemplate.queryForObject("select * from tb_test1 where id = 100",
new RowMapper(){
@Override
public Object mapRow(ResultSet rs, int rowNum)throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
return user;
}
}
);
}
public User queryForObject4(User user) {
return (User) jdbcTemplate.queryForObject("select * from tb_test1 where id = ?",
new Object[]{user.getId()},
User.class); //class是結果資料的java型別 實際上這裡是做反射,將查詢的結果和User進行對應複製
}
public User queryForObject5(User user) {
return (User) jdbcTemplate.queryForObject(
"select * from tb_test1 where id = ?",
new Object[]{user.getId()},
new RowMapper(){
@Override
public Object mapRow(ResultSet rs,int rowNum)throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
return user;
}
}); //class是結果資料的java型別
}
@Override
public User queryForObject(User user) {
//方法有返回值
return (User) jdbcTemplate.queryForObject("select * from tb_test1 where id = ?",
new Object[]{user.getId()},
new int[]{java.sql.Types.INTEGER},
new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
return user;
}
}
);
}
@SuppressWarnings("unchecked")
public List<User> queryForList1(User user) {
return (List<User>) jdbcTemplate.queryForList("select * from tb_test1 where username = ?",
new Object[]{user.getUsername()},
User.class);
}
@SuppressWarnings("unchecked")
public List<String> queryForList2(User user) {
return (List<String>) jdbcTemplate.queryForList("select username from tb_test1 where sex = ?",
new Object[]{user.getSex()},
String.class);
}
@SuppressWarnings("unchecked")
//最全的引數查詢
public List<User> queryForList3(User user) {
return (List<User>) jdbcTemplate.queryForList("select * from tb_test1 where username = ?",
new Object[]{user.getUsername()},
new int[]{java.sql.Types.VARCHAR},
User.class);
}
//通過RowCallbackHandler對Select語句得到的每行記錄進行解析,併為其建立一個User資料物件。實現了手動的OR對映。
public User queryUserById4(String id){
final User user = new User();
//該方法返回值為void
this.jdbcTemplate.query("select * from tb_test1 where id = ?",
new Object[] { id },
new RowCallbackHandler() {
@Override
public void processRow(ResultSet rs) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
}
});
return user;
}
@SuppressWarnings("unchecked")
@Override
public List<User> list(User user) {
return jdbcTemplate.query("select * from tb_test1 where username like '%?%'",
new Object[]{user.getUsername()},
new int[]{java.sql.Types.VARCHAR},
new RowMapper(){
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
return user;
}
});
}
//批量操作 適合於增、刪、改操作
public int[] batchUpdate(final List users) {
int[] updateCounts = jdbcTemplate.batchUpdate(
"update tb_test1 set username = ?, password = ? where id = ?",
new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, ((User)users.get(i)).getUsername());
ps.setString(2, ((User)users.get(i)).getPassword());
ps.setLong(3, ((User)users.get(i)).getId());
}
@Override
public int getBatchSize() {
return users.size();
}
}
);
return updateCounts;
}
//呼叫儲存過程
public void callProcedure(int id){
this.jdbcTemplate.update("call SUPPORT.REFRESH_USERS_SUMMARY(?)", new Object[]{Long.valueOf(id)});
}
也可以參考這篇:http://blog.csdn.net/dyllove98/article/details/7772463