Spring框架

8.3 测试数据准备

8.3.1 需求

8.3.2 数据库表

CREATE TABLE book (

  isbn VARCHAR (50) PRIMARY KEY,

  book_name VARCHAR (100),

  price INT

) ;

 

CREATE TABLE book_stock (

  isbn VARCHAR (50) PRIMARY KEY,

  stock INT,

  CHECK (stock > 0)

) ;

 

CREATE TABLE account (

  username VARCHAR (50) PRIMARY KEY,

  balance INT,

  CHECK (balance > 0)

) ;

 

INSERT INTO account (`username`,`balance`) VALUES ('Tom',100000);

INSERT INTO account (`username`,`balance`) VALUES ('Jerry',150000);

 

INSERT INTO book (`isbn`,`book_name`,`price`) VALUES ('ISBN-001','book01',100);

INSERT INTO book (`isbn`,`book_name`,`price`) VALUES ('ISBN-002','book02',200);

INSERT INTO book (`isbn`,`book_name`,`price`) VALUES ('ISBN-003','book03',300);

INSERT INTO book (`isbn`,`book_name`,`price`) VALUES ('ISBN-004','book04',400);

INSERT INTO book (`isbn`,`book_name`,`price`) VALUES ('ISBN-005','book05',500);

 

INSERT INTO book_stock (`isbn`,`stock`) VALUES ('ISBN-001',1000);

INSERT INTO book_stock (`isbn`,`stock`) VALUES ('ISBN-002',2000);

INSERT INTO book_stock (`isbn`,`stock`) VALUES ('ISBN-003',3000);

INSERT INTO book_stock (`isbn`,`stock`) VALUES ('ISBN-004',4000);

INSERT INTO book_stock (`isbn`,`stock`) VALUES ('ISBN-005',5000);

 

8.4 初步实现

  • 配置文件

<!-- 配置事务管理器 -->

<bean id="transactionManager"

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

         <property name="dataSource" ref="dataSource"/>       

</bean>

 

<!-- 启用事务注解 -->

<tx:annotation-driven transaction-manager="transactionManager"/>

 

  • 在需要进行事务控制的方法上加注解 @Transactional