何为声明式?
声明式有一个对立面叫做:编程式
所谓声明式简单来说就是不用敲代码了使用注解的方式告诉框架要去做这个事情。
声明式事务的优缺点:
优点:代码量少,实现起来快
缺点:封装起来了,一旦出现了问题要调整起来比较麻烦
编程式事务的优缺点:
优点:排错及调整起来方便
缺点:需要写的代码量比较多
一、JdbcTemplate
示例数据库准备
本地建立mysql数据库:spring_tx
在这个库中新增表及初始数据:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '用户id',`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户名',`age` int(0) NULL DEFAULT NULL COMMENT '年龄',`balance` decimal(10, 2) NULL DEFAULT NULL COMMENT '余额',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES (1, 'zhangsan', 18, 10000.00);
INSERT INTO `account` VALUES (2, 'lisi', 20, 10000.00);
INSERT INTO `account` VALUES (3, 'wangwu', 16, 10000.00);-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (`id` int(0) NOT NULL AUTO_INCREMENT COMMENT '图书id',`bookName` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '图书名',`price` decimal(10, 2) NULL DEFAULT NULL COMMENT '单价',`stock` int(0) NULL DEFAULT NULL COMMENT '库存量',PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (1, '剑指Java', 100.00, 100);
INSERT INTO `book` VALUES (2, '剑指大数据', 100.00, 100);
INSERT INTO `book` VALUES (3, '剑指Offer', 100.00, 100);SET FOREIGN_KEY_CHECKS = 1;
pom依赖
<dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!-- lombok依赖,方便我们后续后成JavaBean,与JdbcTemplate无关 -->
<dependency><groupId>org.projectlomb