* 上一篇文章已经做了入门介绍:https://blog.csdn.net/Shen_R/article/details/105216907
* 接下来介绍XML版本的控制写法:
jdbc.user=root
jdbc.password=root
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/tx
jdbc.driverClass=com.mysql.jdbc.Driver
import com.atguigu.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TxTest {
ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-config.xml");
@Test
public void test(){
BookService bookService = ioc.getBean(BookService.class);
bookService.checkout("Tom","ISBN-001");
System.out.println("结账完成!");
}
}
package com.atguigu.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
public class BookDao {
JdbcTemplate jdbcTemplate;
public void updateBalance(String userName, double price){
String sql = "UPDATE account SET balance = balance - ? WHERE username = ?";
jdbcTemplate.update(sql, price, userName);
}
public Double getPrice(String isbn){
String sql = "SELECT price FROM book WHERE isbn = ?";
return jdbcTemplate.queryForObject(sql, Double.class, isbn);
}
public void updateStock(String isbn){
String sql = "UPDATE book_stock SET stock = stock-1 WHERE isbn = ?";
jdbcTemplate.update(sql, isbn);
}
}
package com.atguigu.service;
import com.atguigu.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.FileNotFoundException;
public class BookService {
@Autowired
BookDao bookDao;
public void checkout(String username, String isbn){
// 第一步:减库存
bookDao.updateStock(isbn);
// 第二步:减余额,先查询图书价格
Double price = bookDao.getPrice(isbn);
bookDao.updateBalance(username, price);
}
}