Chinaunix首页 | 论坛 | 博客
  • 博客访问: 438682
  • 博文数量: 161
  • 博客积分: 5005
  • 博客等级: 上校
  • 技术积分: 1090
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-20 16:38
文章分类

全部博文(161)

文章存档

2011年(21)

2010年(33)

2009年(89)

2008年(18)

我的朋友

分类: Java

2009-03-21 16:59:24

-----------------------------------------------------------------------------------------------------------
Spring编程式事务管理
直接采用JDBC操作数据库
-----------------------------------------------------------------------------------------------------------
   drop TABLE sampledb.orders;
CREATE TABLE sampledb.orders(
`ID` BIGINT NOT NULL,
`ORDER_NUMBER` VARCHAR(15),
`CUSTOMER_ID` BIGINT,
PRIMARY KEY(`ID`)
)
ENGINE = InnoDB;

drop TABLE `sampledb`.`customers`;
CREATE TABLE `sampledb`.`customers` (
   `ID` BIGINT NOT NULL,
`NAME` VARCHAR(45),
PRIMARY KEY(`ID`)
)
ENGINE = InnoDB;


alter table sampledb.orders
add constraint constraint_constraint_fk
foreign key (CUSTOMER_ID)
references sampledb.customers(ID);
   
-----------------------------------------------------------------------------------------------------------
applicationContext.xml
-----------------------------------------------------------------------------------------------------------

    xmlns:xsi=""
    xsi:schemaLocation=" /spring-beans-2.0.xsd">

   
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       
                    value="jdbc:mysql://localhost:3306/SAMPLEDB" />
       
       
   






   

            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       
   






-----------------------------------------------------------------------------------------------------------
Demo.java
-----------------------------------------------------------------------------------------------------------
package test;

import static java.lang.System.err;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
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;

import db.Customers;

public class Demo {
    public static void main(String[] args) {
        XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(
                "applicationContext.xml"));
        DataSource dataSource = (DataSource) factory.getBean("dataSource");

        queryAllBooks(dataSource);
        // 获取PlatformTransactionManager:
        PlatformTransactionManager transManager = (PlatformTransactionManager) factory
                .getBean("transactionManager");
        try {
            doTransaction(transManager, dataSource);
        } finally {
            queryAllBooks(dataSource);
            // System.exit(0);
        }

        System.out.println("END");

    }

    private static void doTransaction(PlatformTransactionManager transManager,
            DataSource dataSource) {
        // 定义TransactionDefinition:
        DefaultTransactionDefinition transDef = new DefaultTransactionDefinition();
        transDef
                .setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        transDef
                .setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        // 开始一个Transaction:
        TransactionStatus ts = transManager.getTransaction(transDef);
        try {
            insertBook(dataSource);
            // insertBook(dataSource);
        } catch (RuntimeException e) {
            e.printStackTrace();
            // 回滚事务:
            transManager.rollback(ts);
            throw e;
        } catch (Error e) {
            e.printStackTrace();
            // 回滚事务:
            transManager.rollback(ts);
            throw e;
        }
        // 提交事务:
        transManager.commit(ts);
    }

    private static void queryAllBooks(DataSource dataSource) {
        List customers = new JdbcTemplate(dataSource).query(
                "select * from customers", new CustomerRowMapper());
        System.err.println("-- All Customers ---------------------------");
        for (Customers customer : customers) {
            System.err.println(" " + customer.getName() + ", by "
                    + customer.getName());
        }
        System.err.println("----------------------------------------");
    }

    private static void insertBook(DataSource dataSource) {
        JdbcTemplate jdbcTemp = new JdbcTemplate(dataSource);
        jdbcTemp.update("insert into customers(id, name) values(?, ?)",
                new Object[] { 123, "New Author" });
    }
}

class CustomerRowMapper implements RowMapper {

    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
        Customers book = new Customers();
        book.setId(Long.parseLong(rs.getString("id")));
        book.setName(rs.getString("name"));

        return book;
    }
}
阅读(1203) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~