Skip to content

Commit

Permalink
feat: spring data 示例
Browse files Browse the repository at this point in the history
  • Loading branch information
dunwu committed Aug 14, 2023
1 parent a1fedc0 commit ae06bfd
Show file tree
Hide file tree
Showing 58 changed files with 907 additions and 633 deletions.
2 changes: 1 addition & 1 deletion codes/data/jdbc/basics/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# spring-boot-data-jdbc

[//]: # '> **本项目演示 Spring Boot 以 JDBC 方式访问关系型数据库,通过 `JdbcTemplate` 执行基本的 CRUD 操作。**'
> **本项目演示 Spring Boot 以 JDBC 方式访问关系型数据库,通过 `JdbcTemplate` 执行基本的 CRUD 操作。**
## 使用说明

Expand Down
19 changes: 4 additions & 15 deletions codes/data/jdbc/basics/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.7</version>
<version>2.7.14</version>
</parent>

<groupId>io.github.dunwu.spring</groupId>
Expand All @@ -26,8 +26,8 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
Expand All @@ -36,18 +36,7 @@
<dependency>

This comment has been minimized.

Copy link
@kelseysunhaha

kelseysunhaha Aug 16, 2023

898998

This comment has been minimized.

Copy link
@kelseysunhaha

kelseysunhaha Aug 16, 2023

01234567890

<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.21</version>
</dependency>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.github.dunwu</groupId>
<artifactId>dunwu-dependencies</artifactId>
<version>1.1.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ public UserDaoImpl(JdbcTemplate jdbcTemplate) {

@Override
public void insert(User user) {
jdbcTemplate.update("INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)",
jdbcTemplate.update("INSERT INTO `t_user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)",
user.getName(), user.getAge(), user.getAddress(), user.getEmail());
}

@Override
@Transactional(rollbackFor = Exception.class)
public void batchInsert(List<User> users) {
String sql = "INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)";
String sql = "INSERT INTO `t_user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)";

List<Object[]> params = new ArrayList<>();

Expand All @@ -45,39 +45,39 @@ public void batchInsert(List<User> users) {

@Override
public void deleteByName(String name) {
jdbcTemplate.update("DELETE FROM user WHERE name = ?", name);
jdbcTemplate.update("DELETE FROM `t_user` WHERE `name` = ?", name);
}

@Override
@Transactional(rollbackFor = Exception.class)
public void deleteAll() {
jdbcTemplate.execute("DELETE FROM user");
jdbcTemplate.execute("DELETE FROM `t_user`");
}

@Override
public void update(User user) {
jdbcTemplate.update("UPDATE user SET name=?, age=?, address=?, email=? WHERE id=?",
jdbcTemplate.update("UPDATE `t_user` SET `name`=?, `age`=?, `address`=?, `email`=? WHERE `id`=?",
user.getName(), user.getAge(), user.getAddress(), user.getEmail(), user.getId());
}

@Override
public Integer count() {
try {
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM user", Integer.class);
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM `t_user`", Integer.class);
} catch (EmptyResultDataAccessException e) {
return null;
}
}

@Override
public List<User> list() {
return jdbcTemplate.query("SELECT * FROM user", new BeanPropertyRowMapper<>(User.class));
return jdbcTemplate.query("SELECT * FROM `t_user`", new BeanPropertyRowMapper<>(User.class));
}

@Override
public User queryByName(String name) {
try {
return jdbcTemplate.queryForObject("SELECT * FROM user WHERE name = ?",
return jdbcTemplate.queryForObject("SELECT * FROM `t_user` WHERE `name` = ?",
new BeanPropertyRowMapper<>(User.class), name);
} catch (EmptyResultDataAccessException e) {
return null;
Expand All @@ -91,22 +91,22 @@ public JdbcTemplate getJdbcTemplate() {

@Override
public void truncate() {
jdbcTemplate.execute("TRUNCATE TABLE user");
jdbcTemplate.execute("TRUNCATE TABLE `t_user`");
}

@Override
public void recreateTable() {
jdbcTemplate.execute("DROP TABLE IF EXISTS user");
jdbcTemplate.execute("DROP TABLE IF EXISTS `t_user`");

String sqlStatement =
"CREATE TABLE user (\n"
+ " id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID',\n"
+ " name VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名',\n"
+ " age INT(3) NOT NULL DEFAULT 0 COMMENT '年龄',\n"
+ " address VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址',\n"
+ " email VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件',\n"
+ " PRIMARY KEY (id),\n"
+ " UNIQUE (name)\n"
"CREATE TABLE `t_user` (\n"
+ " `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID',\n"
+ " `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名',\n"
+ " `age` INT(3) NOT NULL DEFAULT 0 COMMENT '年龄',\n"
+ " `address` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址',\n"
+ " `email` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件',\n"
+ " PRIMARY KEY (`id`),\n"
+ " UNIQUE (`name`)\n"
+ ");";
jdbcTemplate.execute(sqlStatement);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,19 @@
*/
public interface UserDaoTxService {

void noTransaction();
/**
* 无事务示例
*/
void noTransaction(User entity);

void withTransaction();
/**
* 声明式事务示例
*/
void withTransaction(User entity);

/**
* 编程式事务示例
*/
void withTransaction2(User entity);

}
Original file line number Diff line number Diff line change
@@ -1,32 +1,64 @@
package example.spring.data.jdbc;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

/**
* 事务服务
*
* @author <a href="mailto:[email protected]">Zhang Peng</a>
* @since 2023-01-22
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDaoTxServiceImpl implements UserDaoTxService {

private final UserDao userDao;
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;

@Override
public void noTransaction() {
userDao.insert(new User("王五", 18, "深圳", "[email protected]"));
public void noTransaction(User entity) {
userDao.insert(entity);
log.info("插入一条记录: {}", JSONUtil.toJsonStr(entity));
throw new RuntimeException("强制异常");
}

@Override
@Transactional(rollbackFor = Exception.class)
public void withTransaction() {
userDao.insert(new User("赵六", 18, "深圳", "[email protected]"));
throw new RuntimeException("强制异常");
@Transactional(rollbackFor = RollbackException.class)
public void withTransaction(User entity) {
userDao.insert(entity);
log.info("插入一条记录: {}", JSONUtil.toJsonStr(entity));
throw new RollbackException("强制异常");
}

@Override
public void withTransaction2(User entity) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
jdbcTemplate.update("INSERT INTO `t_user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)",
entity.getName(), entity.getAge(), entity.getAddress(), entity.getEmail());
log.info("写入一条记录:{}", entity);
status.setRollbackOnly();
}
});
}

static class RollbackException extends RuntimeException {

public RollbackException(String message) {
super(message);
}

}

}
4 changes: 2 additions & 2 deletions codes/data/jdbc/basics/src/main/resources/sql/data.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
-- https://dunwu.github.io/db-tutorial/#/sql/mysql/README
-- -------------------------------------------------------------------

INSERT INTO `user` (`name`, `age`, `address`, `email`)
INSERT INTO `t_user` (`name`, `age`, `address`, `email`)
VALUES ('张三', 18, '北京', '[email protected]');
INSERT INTO `user` (`name`, `age`, `address`, `email`)
INSERT INTO `t_user` (`name`, `age`, `address`, `email`)
VALUES ('李四', 19, '上海', '[email protected]');
4 changes: 2 additions & 2 deletions codes/data/jdbc/basics/src/main/resources/sql/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
-- -------------------------------------------------------------------

-- 创建用户表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID',
`name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名',
`age` TINYINT(3) NOT NULL DEFAULT 0 COMMENT '年龄',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
Expand All @@ -15,6 +16,7 @@

@Slf4j
@Rollback
@DisplayName("Spring JDBC 基本 CRUD 示例")
@SpringBootTest(classes = { DataJdbcApplication.class })
public class DataJdbcTests {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
Expand All @@ -16,6 +17,7 @@
*/
@Slf4j
@Rollback
@DisplayName("Spring 事务示例")
@SpringBootTest(classes = { DataJdbcApplication.class })
public class DataTxTests {

Expand All @@ -25,34 +27,51 @@ public class DataTxTests {
@Autowired
private UserDaoTxService userDaoTxService;

@BeforeEach
public void before() {
userDao.truncate();
}

@Test
@DisplayName("没有事务的例子")
@DisplayName("无事务示例")
public void noTransaction() {
Integer oldNum = userDao.count();

User entity = new User("王五", 18, "深圳", "[email protected]");
try {
userDaoTxService.noTransaction();
userDaoTxService.noTransaction(entity);
} catch (Exception e) {
// do nothing
}

Integer newNum = userDao.count();
Assertions.assertNotEquals(oldNum, newNum);
User record = userDao.queryByName("王五");
Assertions.assertNotNull(record);
}

@Test
@DisplayName("有事务的例子")
@DisplayName("声明式事务示例")
public void withTransaction() {
Integer oldNum = userDao.count();
User entity = new User("赵六", 18, "深圳", "[email protected]");
try {
userDaoTxService.withTransaction(entity);
} catch (Exception e) {
// do nothing
}

User record = userDao.queryByName("赵六");
Assertions.assertNull(record);
}

@Test
@DisplayName("编程式事务示例")
public void withTransaction2() {
User entity = new User("钱七", 20, "南京", "[email protected]");
try {
userDaoTxService.withTransaction();
userDaoTxService.withTransaction2(entity);
} catch (Exception e) {
// do nothing
}

Integer newNum = userDao.count();
Assertions.assertEquals(oldNum, newNum);
User record = userDao.queryByName("钱七");
Assertions.assertNull(record);
}

}
Loading

0 comments on commit ae06bfd

Please sign in to comment.