Spring 如何进行编程式事务管理呢?

 转自:

Spring 如何进行编程式事务管理呢?

下文将采用示例的方式,讲述编程式事务管理的方法分享,如下所示:

  1. 创建 SpringDemo 项目
  2. 在 src 目录下创建 com.java265 包
  3. 导入 Spring 相关 JAR 包及 mysql-connector-java.x.x.x.jar 包
  4. 在 com.java265 包下创建 User、UserDao、UserDaoImpl、Beans.xml 和 MainApp
  5. 运行 SpringDemo 项目

User 类

package com.java265;
public class User {
    private int id;
    private String name;
    private int age;
    public User() {
    }
    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    
    // 省略set和get方法
}

UserDao类

package com.java265;
import java.util.List;
public interface UserDao {
    /**
     * 初始化User表
     */
    void createUserTable();
    /**
     * 保存用户
     */
    void saveUser(User user);
    /**
     * 查询用户
     */
    List listUser();
}

UserDaoImpl 类

package com.java265;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate;
    private UserDao userDao;
    private PlatformTransactionManager transactionManager;
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    public UserDao getUserDao() {
        return userDao;
    }
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    public void setDataSource(DataSource datasource) {
        this.jdbcTemplate = new JdbcTemplate(datasource);
    }
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
    @Override
    public void createUserTable() {
        this.jdbcTemplate.execute("CREATE TABLE `user` (\r\n" + "  `id` int(11) NOT NULL AUTO_INCREMENT,\r\n"
                + "  `name` varchar(50) DEFAULT NULL,\r\n" + "  `age` int(11) DEFAULT NULL,\r\n"
                + "  PRIMARY KEY (`id`)\r\n" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
    }
    @Override
    public void saveUser(User user) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        // getTransaction()用于启动事务,返回TransactionStatus实例对象
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            this.jdbcTemplate.update("INSERT INTO USER(NAME,age) VALUES (?,?)", user.getName(), user.getAge());
            transactionManager.commit(status);
            System.out.println("commit!");
        } catch (Exception e) {
            System.out.println("Error in creating record, rolling back");
            transactionManager.rollback(status);
            throw e;
        }
    }
    @Override
    public List listUser() {
        List users = this.jdbcTemplate.query("SELECT NAME,age FROM USER", new RowMapper() {
            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
                User user = new User();
                user.setName(rs.getString("name"));
                user.setAge(rs.getInt("age"));
                return user;
            }
        });
        return users;
    }
}

Beans.xml



    
    
        
        
        
        
        
        
        
        
    
    
    
        
        
    
    
        
    
    
        
        
    


MainApp 类

package com.java265;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");
        UserDao dao = (UserDao) ctx.getBean("userdao");
        dao.createUserTable();
        dao.saveUser(new User("java265", 888));
        dao.saveUser(new User("baidu", 999));
        List users = dao.listUser();
        for (User user : users) {
            System.out.println("姓名:" + user.getName() + "\t年龄:" + user.getAge());
        }
    }
}

运行结果---
commit!
commit!
姓名:java265 年龄:888
姓名:baidu 年龄:999

你可能感兴趣的:(Spring,spring)