diff --git a/codes/data/jdbc/basics/README.md b/codes/data/jdbc/basics/README.md index feb3f785..7745c903 100644 --- a/codes/data/jdbc/basics/README.md +++ b/codes/data/jdbc/basics/README.md @@ -1,6 +1,6 @@ # spring-boot-data-jdbc -[//]: # '> **本项目演示 Spring Boot 以 JDBC 方式访问关系型数据库,通过 `JdbcTemplate` 执行基本的 CRUD 操作。**' +> **本项目演示 Spring Boot 以 JDBC 方式访问关系型数据库,通过 `JdbcTemplate` 执行基本的 CRUD 操作。** ## 使用说明 diff --git a/codes/data/jdbc/basics/pom.xml b/codes/data/jdbc/basics/pom.xml index f41cf720..ae848d8e 100644 --- a/codes/data/jdbc/basics/pom.xml +++ b/codes/data/jdbc/basics/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.7 + 2.7.14 io.github.dunwu.spring @@ -26,8 +26,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.projectlombok @@ -36,18 +36,7 @@ cn.hutool hutool-all + 5.8.21 - - - - - io.github.dunwu - dunwu-dependencies - 1.1.0 - pom - import - - - diff --git a/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/TransactionDemo.java b/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/TransactionDemo.java deleted file mode 100644 index 9ec24dd7..00000000 --- a/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/TransactionDemo.java +++ /dev/null @@ -1,37 +0,0 @@ -package example.spring.data.jdbc; - -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Component; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallbackWithoutResult; -import org.springframework.transaction.support.TransactionTemplate; - -/** - * 编程式事务示例 - * - * @author Zhang Peng - * @since 2023-01-22 - */ -@Slf4j -@Component -@RequiredArgsConstructor -public class TransactionDemo { - - private final JdbcTemplate jdbcTemplate; - private final TransactionTemplate transactionTemplate; - - public void rollback(User user) { - transactionTemplate.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) { - jdbcTemplate.update("INSERT INTO `user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)", - user.getName(), user.getAge(), user.getAddress(), user.getEmail()); - log.info("写入一条记录:{}", user); - status.setRollbackOnly(); - } - }); - } - -} diff --git a/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoImpl.java b/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoImpl.java index f726c6f1..d4ef4810 100644 --- a/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoImpl.java +++ b/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoImpl.java @@ -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 users) { - String sql = "INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)"; + String sql = "INSERT INTO `t_user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)"; List params = new ArrayList<>(); @@ -45,25 +45,25 @@ public void batchInsert(List 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; } @@ -71,13 +71,13 @@ public Integer count() { @Override public List 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; @@ -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); } diff --git a/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoTxService.java b/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoTxService.java index d144ec6f..77e8336a 100644 --- a/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoTxService.java +++ b/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoTxService.java @@ -8,8 +8,19 @@ */ public interface UserDaoTxService { - void noTransaction(); + /** + * 无事务示例 + */ + void noTransaction(User entity); - void withTransaction(); + /** + * 声明式事务示例 + */ + void withTransaction(User entity); + + /** + * 编程式事务示例 + */ + void withTransaction2(User entity); } diff --git a/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoTxServiceImpl.java b/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoTxServiceImpl.java index 9a52dbd6..b756b18d 100644 --- a/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoTxServiceImpl.java +++ b/codes/data/jdbc/basics/src/main/java/example/spring/data/jdbc/UserDaoTxServiceImpl.java @@ -1,8 +1,14 @@ 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; /** * 事务服务 @@ -10,23 +16,49 @@ * @author Zhang Peng * @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, "深圳", "user3@163.com")); + 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, "深圳", "user3@163.com")); - 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); + } + } } diff --git a/codes/data/jdbc/basics/src/main/resources/sql/data.sql b/codes/data/jdbc/basics/src/main/resources/sql/data.sql index 7a73cb7c..7c85077f 100644 --- a/codes/data/jdbc/basics/src/main/resources/sql/data.sql +++ b/codes/data/jdbc/basics/src/main/resources/sql/data.sql @@ -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, '北京', 'xxx@163.com'); -INSERT INTO `user` (`name`, `age`, `address`, `email`) +INSERT INTO `t_user` (`name`, `age`, `address`, `email`) VALUES ('李四', 19, '上海', 'xxx@163.com'); diff --git a/codes/data/jdbc/basics/src/main/resources/sql/schema.sql b/codes/data/jdbc/basics/src/main/resources/sql/schema.sql index 8d4c8245..1933a686 100644 --- a/codes/data/jdbc/basics/src/main/resources/sql/schema.sql +++ b/codes/data/jdbc/basics/src/main/resources/sql/schema.sql @@ -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 '年龄', diff --git a/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataJdbcTests.java b/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataJdbcTests.java index 5d0ef5fc..b545235e 100644 --- a/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataJdbcTests.java +++ b/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataJdbcTests.java @@ -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; @@ -15,6 +16,7 @@ @Slf4j @Rollback +@DisplayName("Spring JDBC 基本 CRUD 示例") @SpringBootTest(classes = { DataJdbcApplication.class }) public class DataJdbcTests { diff --git a/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataTxTests.java b/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataTxTests.java index 88f03462..e5d23ae1 100644 --- a/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataTxTests.java +++ b/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataTxTests.java @@ -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; @@ -16,6 +17,7 @@ */ @Slf4j @Rollback +@DisplayName("Spring 事务示例") @SpringBootTest(classes = { DataJdbcApplication.class }) public class DataTxTests { @@ -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, "深圳", "wangwu@163.com"); 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, "深圳", "zhaoliu@163.com"); + 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, "南京", "qianqi@163.com"); 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); } } diff --git a/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataTxTests2.java b/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataTxTests2.java deleted file mode 100644 index eeb9a64a..00000000 --- a/codes/data/jdbc/basics/src/test/java/example/spring/data/jdbc/DataTxTests2.java +++ /dev/null @@ -1,29 +0,0 @@ -package example.spring.data.jdbc; - -import lombok.extern.slf4j.Slf4j; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.annotation.Rollback; - -/** - * 编程式事务测试例 - * - * @author Zhang Peng - * @since 2023-01-22 - */ -@Slf4j -@Rollback -@SpringBootTest(classes = { DataJdbcApplication.class }) -public class DataTxTests2 { - - @Autowired - private TransactionDemo transactionDemo; - - @Test - public void test() { - User user = new User("王五", 18, "南京", "user1@163.com"); - transactionDemo.rollback(user); - } - -} diff --git a/codes/data/jdbc/druid/pom.xml b/codes/data/jdbc/druid/pom.xml index 3e7cd2cc..a647765e 100644 --- a/codes/data/jdbc/druid/pom.xml +++ b/codes/data/jdbc/druid/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.7 + 2.7.14 io.github.dunwu.spring @@ -32,6 +32,10 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.boot + spring-boot-starter-actuator + org.springframework.boot spring-boot-starter-test @@ -40,11 +44,11 @@ com.alibaba druid-spring-boot-starter - 1.2.13 + 1.2.18 - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.projectlombok @@ -53,18 +57,7 @@ cn.hutool hutool-all + 5.8.21 - - - - - io.github.dunwu - dunwu-dependencies - 1.1.0 - pom - import - - - diff --git a/codes/data/jdbc/druid/src/main/java/example/spring/data/jdbc/UserDaoImpl.java b/codes/data/jdbc/druid/src/main/java/example/spring/data/jdbc/UserDaoImpl.java index f726c6f1..d4ef4810 100644 --- a/codes/data/jdbc/druid/src/main/java/example/spring/data/jdbc/UserDaoImpl.java +++ b/codes/data/jdbc/druid/src/main/java/example/spring/data/jdbc/UserDaoImpl.java @@ -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 users) { - String sql = "INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)"; + String sql = "INSERT INTO `t_user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)"; List params = new ArrayList<>(); @@ -45,25 +45,25 @@ public void batchInsert(List 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; } @@ -71,13 +71,13 @@ public Integer count() { @Override public List 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; @@ -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); } diff --git a/codes/data/jdbc/druid/src/main/resources/application.properties b/codes/data/jdbc/druid/src/main/resources/application.properties index d7c36f2e..706ec83f 100644 --- a/codes/data/jdbc/druid/src/main/resources/application.properties +++ b/codes/data/jdbc/druid/src/main/resources/application.properties @@ -2,19 +2,20 @@ spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezo spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver spring.datasource.username = root spring.datasource.password = root -# 最大连接数 -spring.datasource.druid.maxActive = 10 -# 最小连接数 -spring.datasource.druid.minIdle = 1 # 初始连接数 -spring.datasource.druid.initialSize = 1 +spring.datasource.druid.initial-size = 2 +# 最小连接数 +spring.datasource.druid.min-idle = 2 +# 最大连接数 +spring.datasource.druid.max-active = 10 # 检测连接的间隔时间,如果连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接,单位是毫秒 -spring.datasource.druid.timeBetweenEvictionRunsMillis = 60000 +spring.datasource.druid.time-between-eviction-runs-millis = 60000 # 连接保持空闲而不被驱逐的最小时间,单位是毫秒 -spring.datasource.druid.minEvictableIdleTimeMillis = 300000 +spring.datasource.druid.min-evictable-idle-time-millis = 300000 # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 -spring.datasource.druid.testOnBorrow = true -spring.datasource.druid.testOnReturn = false +spring.datasource.druid.test-on-borrow = true +spring.datasource.druid.test-on-return = true +spring.datasource.druid.test-while-idle = true # 开启 WebStatFilter spring.datasource.druid.web-stat-filter.enabled = true # 开启 StatViewServlet diff --git a/codes/data/jdbc/druid/src/main/resources/sql/data.sql b/codes/data/jdbc/druid/src/main/resources/sql/data.sql index 7a73cb7c..7c85077f 100644 --- a/codes/data/jdbc/druid/src/main/resources/sql/data.sql +++ b/codes/data/jdbc/druid/src/main/resources/sql/data.sql @@ -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, '北京', 'xxx@163.com'); -INSERT INTO `user` (`name`, `age`, `address`, `email`) +INSERT INTO `t_user` (`name`, `age`, `address`, `email`) VALUES ('李四', 19, '上海', 'xxx@163.com'); diff --git a/codes/data/jdbc/druid/src/main/resources/sql/schema.sql b/codes/data/jdbc/druid/src/main/resources/sql/schema.sql index 8d4c8245..1933a686 100644 --- a/codes/data/jdbc/druid/src/main/resources/sql/schema.sql +++ b/codes/data/jdbc/druid/src/main/resources/sql/schema.sql @@ -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 '年龄', diff --git a/codes/data/jdbc/multi-datasource/pom.xml b/codes/data/jdbc/multi-datasource/pom.xml index d20c5356..2d0387dc 100644 --- a/codes/data/jdbc/multi-datasource/pom.xml +++ b/codes/data/jdbc/multi-datasource/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.7 + 2.7.14 io.github.dunwu.spring @@ -26,8 +26,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j com.h2database diff --git a/codes/data/jdbc/multi-datasource/src/main/java/example/spring/data/jdbc/H2UserDaoImpl.java b/codes/data/jdbc/multi-datasource/src/main/java/example/spring/data/jdbc/H2UserDaoImpl.java index 6369bc4b..9f4326e3 100644 --- a/codes/data/jdbc/multi-datasource/src/main/java/example/spring/data/jdbc/H2UserDaoImpl.java +++ b/codes/data/jdbc/multi-datasource/src/main/java/example/spring/data/jdbc/H2UserDaoImpl.java @@ -27,14 +27,14 @@ public H2UserDaoImpl(@Qualifier("h2JdbcTemplate") 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 users) { - String sql = "INSERT INTO `user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)"; + String sql = "INSERT INTO `t_user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)"; List params = new ArrayList<>(); @@ -46,25 +46,25 @@ public void batchInsert(List 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; } @@ -72,13 +72,13 @@ public Integer count() { @Override public List 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; @@ -92,15 +92,15 @@ 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" + "CREATE TABLE `t_user` (\n" + " `id` INT AUTO_INCREMENT NOT NULL COMMENT 'ID',\n" + " `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名',\n" + " `age` INT NOT NULL DEFAULT 0 COMMENT '年龄',\n" diff --git a/codes/data/jdbc/multi-datasource/src/main/java/example/spring/data/jdbc/MysqlUserDaoImpl.java b/codes/data/jdbc/multi-datasource/src/main/java/example/spring/data/jdbc/MysqlUserDaoImpl.java index 8fb8f064..7d1db2ed 100644 --- a/codes/data/jdbc/multi-datasource/src/main/java/example/spring/data/jdbc/MysqlUserDaoImpl.java +++ b/codes/data/jdbc/multi-datasource/src/main/java/example/spring/data/jdbc/MysqlUserDaoImpl.java @@ -27,14 +27,14 @@ public MysqlUserDaoImpl(@Qualifier("mysqlJdbcTemplate") JdbcTemplate jdbcTemplat @Override public void insert(User user) { - jdbcTemplate.update("INSERT INTO `user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)", user.getName(), - user.getAge(), user.getAddress(), user.getEmail()); + 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 users) { - String sql = "INSERT INTO `user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)"; + String sql = "INSERT INTO `t_user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)"; List params = new ArrayList<>(); @@ -46,25 +46,25 @@ public void batchInsert(List 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`=?", user.getName(), - user.getAge(), user.getAddress(), user.getEmail(), user.getId()); + 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; } @@ -72,13 +72,13 @@ public Integer count() { @Override public List 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; @@ -92,14 +92,15 @@ 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" + String sqlStatement = + "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" diff --git a/codes/data/jdbc/multi-datasource/src/main/resources/sql/data.sql b/codes/data/jdbc/multi-datasource/src/main/resources/sql/data.sql index 7a73cb7c..7c85077f 100644 --- a/codes/data/jdbc/multi-datasource/src/main/resources/sql/data.sql +++ b/codes/data/jdbc/multi-datasource/src/main/resources/sql/data.sql @@ -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, '北京', 'xxx@163.com'); -INSERT INTO `user` (`name`, `age`, `address`, `email`) +INSERT INTO `t_user` (`name`, `age`, `address`, `email`) VALUES ('李四', 19, '上海', 'xxx@163.com'); diff --git a/codes/data/jdbc/multi-datasource/src/main/resources/sql/schema-h2.sql b/codes/data/jdbc/multi-datasource/src/main/resources/sql/schema-h2.sql index c2e02d46..36e9e748 100644 --- a/codes/data/jdbc/multi-datasource/src/main/resources/sql/schema-h2.sql +++ b/codes/data/jdbc/multi-datasource/src/main/resources/sql/schema-h2.sql @@ -5,8 +5,8 @@ -- ------------------------------------------------------------------- -- 创建用户表 -DROP TABLE IF EXISTS `user`; -CREATE TABLE `user` ( +DROP TABLE IF EXISTS `t_user`; +CREATE TABLE `t_user` ( `id` INT AUTO_INCREMENT NOT NULL COMMENT 'ID', `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名', `age` INT NOT NULL DEFAULT 0 COMMENT '年龄', diff --git a/codes/data/jdbc/multi-datasource/src/main/resources/sql/schema.sql b/codes/data/jdbc/multi-datasource/src/main/resources/sql/schema.sql index 8d4c8245..1933a686 100644 --- a/codes/data/jdbc/multi-datasource/src/main/resources/sql/schema.sql +++ b/codes/data/jdbc/multi-datasource/src/main/resources/sql/schema.sql @@ -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 '年龄', diff --git a/codes/data/jdbc/xml/pom.xml b/codes/data/jdbc/xml/pom.xml index 2da1123b..3115a999 100644 --- a/codes/data/jdbc/xml/pom.xml +++ b/codes/data/jdbc/xml/pom.xml @@ -26,15 +26,11 @@ com.alibaba druid + 1.2.18 - mysql - mysql-connector-java - - - com.h2database - h2 - 2.1.214 + com.mysql + mysql-connector-j @@ -62,10 +58,6 @@ org.springframework spring-jdbc - - org.springframework - spring-tx - org.springframework spring-test @@ -74,38 +66,23 @@ - org.junit.jupiter - junit-jupiter - 5.8.2 - test - - - org.junit.platform - junit-platform-runner - 1.9.0 + junit + junit test org.assertj assertj-core - 3.22.0 test - - io.github.dunwu - dunwu-dependencies - 1.1.0 - pom - import - org.springframework.boot spring-boot-dependencies - 2.7.7 + 2.7.14 pom import diff --git a/codes/data/jdbc/xml/src/main/java/example/spring/data/jdbc/H2UserDaoImpl.java b/codes/data/jdbc/xml/src/main/java/example/spring/data/jdbc/H2UserDaoImpl.java deleted file mode 100644 index 6369bc4b..00000000 --- a/codes/data/jdbc/xml/src/main/java/example/spring/data/jdbc/H2UserDaoImpl.java +++ /dev/null @@ -1,115 +0,0 @@ -package example.spring.data.jdbc; - -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.jdbc.core.BeanPropertyRowMapper; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import java.util.ArrayList; -import java.util.List; - -/** - * user 表 Dao 接口的 H2 实现 - * - * @author Zhang Peng - * @since 2019-10-12 - */ -@Repository("h2UserDao") -public class H2UserDaoImpl implements UserDao { - - private final JdbcTemplate jdbcTemplate; - - public H2UserDaoImpl(@Qualifier("h2JdbcTemplate") JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - @Override - public void insert(User user) { - jdbcTemplate.update("INSERT INTO `user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)", - user.getName(), user.getAge(), user.getAddress(), user.getEmail()); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void batchInsert(List users) { - String sql = "INSERT INTO `user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)"; - - List params = new ArrayList<>(); - - users.forEach(user -> { - params.add(new Object[] { user.getName(), user.getAge(), user.getAddress(), user.getEmail() }); - }); - jdbcTemplate.batchUpdate(sql, params); - } - - @Override - public void deleteByName(String name) { - jdbcTemplate.update("DELETE FROM `user` WHERE name = ?", name); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void deleteAll() { - jdbcTemplate.execute("DELETE FROM `user`"); - } - - @Override - public void update(User user) { - jdbcTemplate.update("UPDATE `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); - } catch (EmptyResultDataAccessException e) { - return null; - } - } - - @Override - public List list() { - return jdbcTemplate.query("SELECT * FROM `user`", new BeanPropertyRowMapper<>(User.class)); - } - - @Override - public User queryByName(String name) { - try { - return jdbcTemplate.queryForObject("SELECT * FROM `user` WHERE name = ?", - new BeanPropertyRowMapper<>(User.class), name); - } catch (EmptyResultDataAccessException e) { - return null; - } - } - - @Override - public JdbcTemplate getJdbcTemplate() { - return jdbcTemplate; - } - - @Override - public void truncate() { - jdbcTemplate.execute("TRUNCATE TABLE `user`"); - } - - @Override - public void recreateTable() { - jdbcTemplate.execute("DROP TABLE IF EXISTS `user`;"); - - String sqlStatement = - "CREATE TABLE `user` (\n" - + " `id` INT AUTO_INCREMENT NOT NULL COMMENT 'ID',\n" - + " `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名',\n" - + " `age` INT 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); - } - -} diff --git a/codes/data/jdbc/xml/src/main/java/example/spring/data/jdbc/MysqlUserDaoImpl.java b/codes/data/jdbc/xml/src/main/java/example/spring/data/jdbc/MysqlUserDaoImpl.java index 54bcf86c..40dd83b6 100644 --- a/codes/data/jdbc/xml/src/main/java/example/spring/data/jdbc/MysqlUserDaoImpl.java +++ b/codes/data/jdbc/xml/src/main/java/example/spring/data/jdbc/MysqlUserDaoImpl.java @@ -12,6 +12,7 @@ /** * user 表 Dao 接口的 Mysql 实现 + * * @author Zhang Peng * @since 2019-10-12 */ @@ -26,14 +27,14 @@ public MysqlUserDaoImpl(@Qualifier("mysqlJdbcTemplate") JdbcTemplate jdbcTemplat @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 users) { - String sql = "INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)"; + String sql = "INSERT INTO `t_user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)"; List params = new ArrayList<>(); @@ -45,25 +46,25 @@ public void batchInsert(List 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; } @@ -71,13 +72,13 @@ public Integer count() { @Override public List 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; @@ -91,22 +92,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); } diff --git a/codes/data/jdbc/xml/src/main/resources/sql/data.sql b/codes/data/jdbc/xml/src/main/resources/sql/data.sql index 93b096ae..dd42eb55 100644 --- a/codes/data/jdbc/xml/src/main/resources/sql/data.sql +++ b/codes/data/jdbc/xml/src/main/resources/sql/data.sql @@ -2,7 +2,7 @@ -- 运行本项目的 DML 脚本 -- ------------------------------------------- -INSERT INTO `user` (`name`, `age`, `address`, `email`) +INSERT INTO `t_user` (`name`, `age`, `address`, `email`) VALUES ('张三', 18, '北京', 'xxx@163.com'); -INSERT INTO `user` (`name`, `age`, `address`, `email`) +INSERT INTO `t_user` (`name`, `age`, `address`, `email`) VALUES ('李四', 19, '上海', 'xxx@163.com'); diff --git a/codes/data/jdbc/xml/src/main/resources/sql/schema-h2.sql b/codes/data/jdbc/xml/src/main/resources/sql/schema-h2.sql deleted file mode 100644 index c2e02d46..00000000 --- a/codes/data/jdbc/xml/src/main/resources/sql/schema-h2.sql +++ /dev/null @@ -1,17 +0,0 @@ --- ------------------------------------------------------------------- --- 运行本项目的初始化 DDL 脚本 --- H2 知识点可以参考: --- https://dunwu.github.io/db-tutorial/#/sql/h2 --- ------------------------------------------------------------------- - --- 创建用户表 -DROP TABLE IF EXISTS `user`; -CREATE TABLE `user` ( - `id` INT AUTO_INCREMENT NOT NULL COMMENT 'ID', - `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名', - `age` INT NOT NULL DEFAULT 0 COMMENT '年龄', - `address` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址', - `email` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件', - PRIMARY KEY (`id`), - UNIQUE (`name`) -); diff --git a/codes/data/jdbc/xml/src/main/resources/sql/schema.sql b/codes/data/jdbc/xml/src/main/resources/sql/schema.sql index cb3cdc32..e33dcb5c 100644 --- a/codes/data/jdbc/xml/src/main/resources/sql/schema.sql +++ b/codes/data/jdbc/xml/src/main/resources/sql/schema.sql @@ -3,7 +3,7 @@ -- ------------------------------------------- -- 创建用户表 -CREATE TABLE `user` ( +CREATE TABLE `t_user` ( `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID', `name` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名', `age` INT(3) NOT NULL DEFAULT 0 COMMENT '年龄', diff --git a/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/DruidJdbcTest.java b/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/DruidJdbcTest.java index 0490893a..7f0ab186 100644 --- a/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/DruidJdbcTest.java +++ b/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/DruidJdbcTest.java @@ -3,7 +3,7 @@ import lombok.extern.slf4j.Slf4j; import org.assertj.core.api.Assertions; import org.junit.Before; -import org.junit.jupiter.api.Test; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/H2JdbcTest.java b/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/H2JdbcTest.java deleted file mode 100644 index 90194985..00000000 --- a/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/H2JdbcTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package example.spring.data.jdbc; - -import lombok.extern.slf4j.Slf4j; -import org.assertj.core.api.Assertions; -import org.junit.Before; -import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.ArrayList; -import java.util.List; - -/** - * 测试 H2 JDBC 操作 - * - * @author Zhang Peng - */ -@Slf4j -@SuppressWarnings("all") -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "classpath:data/spring-h2.xml" }) -public class H2JdbcTest { - - @Autowired - @Qualifier("h2UserDao") - private UserDao userDao; - - @Before - public void before() { - userDao.recreateTable(); - } - - @Test - public void insert() { - userDao.insert(new User("张三", 18, "北京", "user1@163.com")); - User linda = userDao.queryByName("张三"); - Assertions.assertThat(linda).isNotNull(); - } - - @Test - public void batchInsert() { - List users = new ArrayList<>(); - users.add(new User("张三", 18, "北京", "user1@163.com")); - users.add(new User("李四", 19, "上海", "user1@163.com")); - users.add(new User("王五", 18, "南京", "user1@163.com")); - users.add(new User("赵六", 20, "武汉", "user1@163.com")); - - userDao.batchInsert(users); - int count = userDao.count(); - Assertions.assertThat(count).isEqualTo(4); - - List list = userDao.list(); - Assertions.assertThat(list).isNotEmpty().hasSize(4); - list.forEach(user -> { - log.info(user.toString()); - }); - } - - @Test - public void delete() { - List users = new ArrayList<>(); - users.add(new User("张三", 18, "北京", "user1@163.com")); - users.add(new User("李四", 19, "上海", "user1@163.com")); - users.add(new User("王五", 18, "南京", "user1@163.com")); - users.add(new User("赵六", 20, "武汉", "user1@163.com")); - userDao.batchInsert(users); - - userDao.deleteByName("张三"); - User user = userDao.queryByName("张三"); - Assertions.assertThat(user).isNull(); - - userDao.deleteAll(); - List list = userDao.list(); - Assertions.assertThat(list).isEmpty(); - } - - @Test - public void update() { - userDao.insert(new User("张三", 18, "北京", "user1@163.com")); - User oldUser = userDao.queryByName("张三"); - oldUser.setName("张三丰"); - userDao.update(oldUser); - User newUser = userDao.queryByName("张三丰"); - Assertions.assertThat(newUser).isNotNull(); - } - -} diff --git a/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/MysqlJdbcTest.java b/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/MysqlJdbcTest.java index 64b30b26..4469931f 100644 --- a/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/MysqlJdbcTest.java +++ b/codes/data/jdbc/xml/src/test/java/example/spring/data/jdbc/MysqlJdbcTest.java @@ -3,12 +3,12 @@ import lombok.extern.slf4j.Slf4j; import org.assertj.core.api.Assertions; import org.junit.Before; -import org.junit.jupiter.api.Test; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; @@ -20,7 +20,7 @@ */ @Slf4j @SuppressWarnings("all") -@RunWith(SpringJUnit4ClassRunner.class) +@RunWith(SpringRunner.class) @ContextConfiguration(locations = { "classpath:data/spring-mysql.xml" }) public class MysqlJdbcTest { diff --git a/codes/data/nosql/mongodb/pom.xml b/codes/data/nosql/mongodb/pom.xml index 1c624d08..d245b6d2 100644 --- a/codes/data/nosql/mongodb/pom.xml +++ b/codes/data/nosql/mongodb/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.7 + 2.7.14 io.github.dunwu.spring @@ -21,9 +21,14 @@ spring-boot-starter-data-mongodb - org.springframework.boot - spring-boot-starter-test - test + com.querydsl + querydsl-mongodb + + + org.mongodb + mongo-java-driver + + @@ -31,52 +36,15 @@ lombok - io.github.dunwu.tool - dunwu-tool-data + cn.hutool + hutool-all + 5.8.21 + - com.querydsl - querydsl-mongodb - - - org.mongodb - mongo-java-driver - - + org.springframework.boot + spring-boot-starter-test + test - - - - - io.github.dunwu - dunwu-dependencies - 1.1.0 - pom - import - - - io.github.dunwu.tool - dunwu-tool - 1.1.0 - pom - import - - - - - - - - - - - - - - - - - - diff --git a/codes/data/nosql/mongodb/src/main/java/example/spring/data/nosql/mongodb/DataMongodbApplication.java b/codes/data/nosql/mongodb/src/main/java/example/spring/data/nosql/mongodb/DataMongodbApplication.java index 9fde1dca..44fec0da 100644 --- a/codes/data/nosql/mongodb/src/main/java/example/spring/data/nosql/mongodb/DataMongodbApplication.java +++ b/codes/data/nosql/mongodb/src/main/java/example/spring/data/nosql/mongodb/DataMongodbApplication.java @@ -2,9 +2,9 @@ import example.spring.data.nosql.mongodb.entity.Customer; import example.spring.data.nosql.mongodb.repository.CustomerRepository; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.bson.Document; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -14,16 +14,15 @@ import javax.annotation.PreDestroy; @Slf4j +@RequiredArgsConstructor @SpringBootApplication public class DataMongodbApplication implements CommandLineRunner { public static final String SYSTEM_PROFILE_DB = "system.profile"; - @Autowired - private MongoOperations operations; + private final MongoOperations operations; - @Autowired - private CustomerRepository repository; + private final CustomerRepository repository; public static void main(String[] args) { SpringApplication.run(DataMongodbApplication.class, args); @@ -86,22 +85,4 @@ private void setProfilingLevel(int level) { operations.executeCommand(new Document("profile", level)); } - // /** - // * Register the {@link BeforeConvertCallback} used to update an {@link ImmutablePerson} before handing over the - // * newly created instance to the actual mapping layer performing the conversion into the store native {@link - // * org.bson.Document} representation. - // * - // * @return a {@link BeforeConvertCallback} for {@link ImmutablePerson}. - // */ - // @Bean - // BeforeConvertCallback beforeConvertCallback() { - // - // return (immutablePerson, collection) -> { - // - // int randomNumber = ThreadLocalRandom.current().nextInt(1, 100); - // - // // withRandomNumber is a so called wither method returning a new instance of the entity with a new value assigned - // return immutablePerson.withRandomNumber(randomNumber); - // }; - // } } diff --git a/codes/data/nosql/mongodb/src/main/resources/application.properties b/codes/data/nosql/mongodb/src/main/resources/application.properties index 179d5666..e273e150 100644 --- a/codes/data/nosql/mongodb/src/main/resources/application.properties +++ b/codes/data/nosql/mongodb/src/main/resources/application.properties @@ -1,7 +1,7 @@ +debug = true spring.data.mongodb.host = localhost spring.data.mongodb.port = 27017 spring.data.mongodb.database = spring-tutorial #spring.data.mongodb.username = #spring.data.mongodb.password = -debug = true #spring.main.allow-circular-references = true diff --git a/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/CompoundRepositoryTests.java b/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/CompoundRepositoryTests.java index f3f45549..4d87a569 100644 --- a/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/CompoundRepositoryTests.java +++ b/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/CompoundRepositoryTests.java @@ -5,7 +5,6 @@ import example.spring.data.nosql.mongodb.entity.User; import example.spring.data.nosql.mongodb.repository.RoleRepository; import example.spring.data.nosql.mongodb.repository.UserRepository; -import io.github.dunwu.tool.util.RandomUtil; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; diff --git a/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/DateUtil.java b/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/DateUtil.java new file mode 100644 index 00000000..71ff458a --- /dev/null +++ b/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/DateUtil.java @@ -0,0 +1,120 @@ +package example.spring.data.nosql.mongodb; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; + +/** + * @author Zhang Peng + * @since 2020-04-08 + */ +public class DateUtil extends cn.hutool.core.date.DateUtil { + + /** + * 将 {@link java.util.Calendar} 转化为 {@link java.util.Date} + * + * @param calendar {@link java.util.Calendar} + * @return {@link java.util.Date} + */ + public static Date toDate(final Calendar calendar) { + return calendar.getTime(); + } + + /** + * 将 {@link java.time.LocalDateTime} 转化为 {@link java.util.Date} + * + * @param localDateTime {@link java.time.LocalDateTime} + * @return {@link java.util.Date} + */ + public static Date toDate(final LocalDateTime localDateTime) { + ZoneId zoneId = ZoneId.systemDefault(); + ZonedDateTime zdt = localDateTime.atZone(zoneId); + return Date.from(zdt.toInstant()); + } + + public static String formatDurationString(Duration duration) { + Duration temp = duration; + StringBuilder sb = new StringBuilder(); + + long days = temp.toDays(); + if (days > 0) { + sb.append(days + "d "); + } + temp = temp.minusDays(days); + + long hours = temp.toHours(); + if (hours > 0) { + sb.append(hours + "h "); + } + temp = temp.minusHours(hours); + + long minutes = temp.toMinutes(); + if (minutes > 0) { + sb.append(minutes + "m "); + } + temp = temp.minusMinutes(minutes); + + long seconds = temp.getSeconds(); + if (seconds > 0) { + sb.append(minutes + "s "); + } + temp = temp.minusSeconds(seconds); + + long millis = temp.toMillis(); + if (millis > 0) { + sb.append(millis + "ms "); + } + temp = temp.minusMillis(millis); + + long nanos = temp.toNanos(); + if (nanos > 0) { + sb.append(nanos + "ns "); + } + return sb.toString(); + } + + public static String formatDurationChineseString(Duration duration) { + Duration temp = duration; + StringBuilder sb = new StringBuilder(); + + long days = temp.toDays(); + if (days > 0) { + sb.append(days + "天 "); + } + temp = temp.minusDays(days); + + long hours = temp.toHours(); + if (hours > 0) { + sb.append(hours + "时 "); + } + temp = temp.minusHours(hours); + + long minutes = temp.toMinutes(); + if (minutes > 0) { + sb.append(minutes + "分 "); + } + temp = temp.minusMinutes(minutes); + + long seconds = temp.getSeconds(); + if (seconds > 0) { + sb.append(minutes + "秒 "); + } + temp = temp.minusSeconds(seconds); + + long millis = temp.toMillis(); + if (millis > 0) { + sb.append(millis + "毫秒 "); + } + temp = temp.minusMillis(millis); + + long nanos = temp.toNanos(); + if (nanos > 0) { + sb.append(nanos + "纳秒 "); + } + return sb.toString(); + } + +} diff --git a/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/RandomUtil.java b/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/RandomUtil.java new file mode 100644 index 00000000..db56d56f --- /dev/null +++ b/codes/data/nosql/mongodb/src/test/java/example/spring/data/nosql/mongodb/RandomUtil.java @@ -0,0 +1,473 @@ +package example.spring.data.nosql.mongodb; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.date.DatePattern; +import cn.hutool.core.util.StrUtil; + +import java.io.UnsupportedEncodingException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +/** + * 随机工具类 + * + * @author xiaoleilu + */ +public class RandomUtil extends cn.hutool.core.util.RandomUtil { + + /** + * 数字全集 + */ + public static final String NUMBER_SAMPLE = "0123456789"; + + /** + * 小写英文字母全集 + */ + public static final String EN_LOWER_CHAR_SAMPLE = "abcdefghijklmnopqrstuvwxyz"; + + /** + * 大写英文字母全集 + */ + public static final String EN_UPPER_CHAR_SAMPLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + /** + * 英文字母全集 + */ + public static final String EN_CHAR_SAMPLE = StrUtil.join("", EN_LOWER_CHAR_SAMPLE, EN_UPPER_CHAR_SAMPLE); + + /** + * 用于随机选的字符和数字 + */ + public static final String WORD_SAMPLE = StrUtil.join("", EN_CHAR_SAMPLE, NUMBER_SAMPLE); + + /** + * 创建{@link java.security.SecureRandom},类提供加密的强随机数生成器 (RNG)
+ * + * @param seed 自定义随机种子 + * @return {@link java.security.SecureRandom} + * @since 4.6.5 + */ + public static SecureRandom createSecureRandom(byte[] seed) { + return (null == seed) ? new SecureRandom() : new SecureRandom(seed); + } + + public static String randomChineseBoyFirstName() { + int count = randomInt(2, 4); + + if (2 == count) { + String secondDictionary = "睿,浩,博,瑞,昊,杰,刚,伟,勇,林,驰,俊,明,清,正,云,鹏,晨,强"; + List names = StrUtil.splitTrim(secondDictionary, ","); + return randomInList(names); + } else if (3 == count) { + String secondDictionary = "子,梓,浩,宇,俊,文,志,晓,小,大"; + String thirdDictionary = + "轩,宇,泽,杰,豪,刚,伟,勇,明,然,涵,蔼,仁,容,德,轩,贤,良,伦,正,清,义,诚,直,道,达,耀,兴,荣,华,丰,余,昌,盛,涛"; + List seconds = StrUtil.splitTrim(secondDictionary, ","); + List thirds = StrUtil.splitTrim(thirdDictionary, ","); + return randomInList(seconds) + randomInList(thirds); + } else { + return ""; + } + } + + public static String randomChineseBoyName() { + return randomChineseLastName() + randomChineseBoyFirstName(); + } + + public static String randomChineseGirlFirstName() { + int count = randomInt(2, 4); + + if (2 == count) { + String secondDictionary = "悦,妍,玥,蕊,欣,洁,雪,静,慧,晴,娜,玟,倩,柔,雅,丽,萍,娟"; + List names = StrUtil.splitTrim(secondDictionary, ","); + return randomInList(names); + } else if (3 == count) { + String secondDictionary = "雨,梓,欣,子,语,馨,思,婉,涵,婷,文,梦,玉,安"; + String thirdDictionary = "涵,萱,怡,彤,琪,文,宁,雪,彤,柔,雅,丽,曼,云,晴,琴,娜"; + List seconds = StrUtil.splitTrim(secondDictionary, ","); + List thirds = StrUtil.splitTrim(thirdDictionary, ","); + return randomInList(seconds) + randomInList(thirds); + } else { + return ""; + } + } + + public static String randomChineseGirlName() { + return randomChineseLastName() + randomChineseGirlFirstName(); + } + + public static String randomChineseLastName() { + String dictionary = + "李,王,张,刘,陈,杨,黄,赵,周,吴,徐,孙,朱,马,胡,郭,林,何,高,梁,郑,罗,宋,谢,唐,韩,曹,许,邓,萧,冯,曾,程,蔡,彭,潘,袁,于,董,余,苏,叶,吕,魏,蒋,田,杜,丁,沈,姜,范,江," + + "傅,钟,卢,汪,戴,崔,任,陆,廖,姚,方,金,邱,夏,谭,韦,贾,邹,石,熊,孟,秦,阎,薛,侯,雷,白,龙,段,郝,孔,邵,史,毛,常,万,顾,赖,武,康,贺,严,尹,钱,施,牛,洪,龚,汤," + + "陶,黎,温,莫,易,樊,乔,文,安,殷,颜,庄,章,鲁,倪,庞,邢,俞,翟,蓝,聂,齐,向,申,葛,岳"; + List names = StrUtil.splitTrim(dictionary, ","); + return randomInList(names); + } + + public static String randomChineseLetterString(final int min, final int max) { + char begin = '\u4E00'; + char end = '\u9FA5'; + StringBuilder sb = new StringBuilder(); + for (int index = begin; index <= end; index++) { + sb.append(index); + } + + int count = randomInt(min, max); + return randomString(sb.toString(), count); + } + + /** + * 获得指定范围内的随机数 + * + * @param min 最小数(包含) + * @param max 最大数(不包含) + * @return 随机数 + */ + public static int randomInt(int min, int max) { + return getRandom().nextInt(min, max); + } + + /** + * 获得一个随机的字符串 + * + * @param sample 随机字符选取的样本 + * @param length 字符串的长度 + * @return 随机字符串 + */ + public static String randomString(final String sample, int length) { + return randomString(sample, 0, length); + } + + public static String randomString(final String sample, final int min, final int max) { + if (StrUtil.isEmpty(sample)) { + return StrUtil.EMPTY; + } + + if (min < 0 || max < 0 || max < min) { + return StrUtil.EMPTY; + } + + int length = getRandom().nextInt(min, max); + final StringBuilder sb = new StringBuilder(length); + int sampleLength = sample.length(); + for (int i = 0; i < length; i++) { + int number = randomInt(sampleLength); + sb.append(sample.charAt(number)); + } + return sb.toString(); + } + + public static String randomChineseName() { + boolean isGirl = randomBoolean(); + return randomChineseName(isGirl); + } + + public static String randomChineseName(final boolean isGirl) { + if (isGirl) { + return randomChineseGirlName(); + } else { + return randomChineseBoyName(); + } + } + + public static String randomChineseSimpleLetterString(final int min, final int max) { + int count = randomInt(min, max); + StringBuilder sb = new StringBuilder(); + for (char index = 0; index < count; index++) { + sb.append(randomChineseSimpleLetter()); + } + return sb.toString(); + } + + /** + * 随机获取任意简体字符 + * + * @see 百度词条-GB2312 + */ + public static String randomChineseSimpleLetter() { + byte[] bytes = new byte[2]; + bytes[0] = (byte) randomInt(0xB0, 0xF7); + bytes[1] = (byte) randomInt(0xA1, 0xFF); + + try { + return new String(bytes, "GB2312"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return ""; + } + + public static String randomDate(final Date min, final Date max) { + return randomDate(min, max, DatePattern.NORM_DATETIME_PATTERN); + } + + public static String randomDate(final Date min, final Date max, final String pattern) { + return randomDate(DateUtil.toLocalDateTime(min), DateUtil.toLocalDateTime(max), pattern); + } + + public static String randomDate(final LocalDateTime min, final LocalDateTime max, final String pattern) { + long minSeconds = min.toEpochSecond(ZoneOffset.UTC); + long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); + long random = ThreadLocalRandom.current().nextLong(minSeconds, maxSeconds); + LocalDateTime localDate = LocalDateTime.ofEpochSecond(random, 1, ZoneOffset.UTC); + return localDate.format(DateTimeFormatter.ofPattern(pattern)); + } + + public static Date randomDate(final LocalDateTime min, final LocalDateTime max) { + long minSeconds = min.toEpochSecond(ZoneOffset.UTC); + long maxSeconds = max.toEpochSecond(ZoneOffset.UTC); + long random = ThreadLocalRandom.current().nextLong(minSeconds, maxSeconds); + LocalDateTime localDate = LocalDateTime.ofEpochSecond(random, 1, ZoneOffset.UTC); + return DateUtil.toDate(localDate); + } + + public static String randomDomain() { + String domain1 = randomString(2, 11); + String domain2 = randomString(2, 4); + return new StringBuilder().append(domain1.toLowerCase()).append(".") + .append(domain2.toLowerCase()).toString(); + } + + /** + * 随机获得列表中的元素 + * + * @param 元素类型 + * @param list 列表 + * @return 随机元素 + */ + public static T randomEle(List list) { + return randomEle(list, list.size()); + } + + /** + * 随机获得列表中的元素 + * + * @param 元素类型 + * @param list 列表 + * @param limit 限制列表的前N项 + * @return 随机元素 + */ + public static T randomEle(List list, int limit) { + return list.get(randomInt(limit)); + } + + /** + * 随机获得数组中的元素 + * + * @param 元素类型 + * @param array 列表 + * @return 随机元素 + * @since 3.3.0 + */ + public static T randomEle(T[] array) { + return randomEle(array, array.length); + } + + /** + * 随机获得数组中的元素 + * + * @param 元素类型 + * @param array 列表 + * @param limit 限制列表的前N项 + * @return 随机元素 + * @since 3.3.0 + */ + public static T randomEle(T[] array, int limit) { + return array[randomInt(limit)]; + } + + /** + * 随机获得列表中的一定量的不重复元素,返回Set + * + * @param 元素类型 + * @param collection 列表 + * @param count 随机取出的个数 + * @return 随机元素 + * @throws IllegalArgumentException 需要的长度大于给定集合非重复总数 + */ + public static Set randomEleSet(Collection collection, int count) { + final ArrayList source = CollectionUtil.distinct(collection); + if (count > source.size()) { + throw new IllegalArgumentException("Count is larger than collection distinct size !"); + } + + final HashSet result = new HashSet<>(count); + int limit = source.size(); + while (result.size() < count) { + result.add(randomEle(source, limit)); + } + + return result; + } + + /** + * 随机获得列表中的一定量元素 + * + * @param 元素类型 + * @param list 列表 + * @param count 随机取出的个数 + * @return 随机元素 + */ + public static List randomEles(List list, int count) { + final List result = new ArrayList<>(count); + int limit = list.size(); + while (result.size() < count) { + result.add(randomEle(list, limit)); + } + + return result; + } + + public static String randomEmail() { + String name = randomString(2, 11); + return new StringBuilder().append(name.toLowerCase()).append("@") + .append(randomDomain()).toString(); + } + + public static > E randomEnum(final Class enumClass) { + List list = new ArrayList<>(EnumSet.allOf(enumClass)); + int index = randomInt(0, list.size()); + return list.get(index); + } + + public static String randomFirstName() { + return randomFirstName(randomBoolean()); + } + + public static String randomFirstName(final boolean isGirl) { + if (isGirl) { + return randomGirlFirstName(); + } else { + return randomBoyFirstName(); + } + } + + public static String randomBoyFirstName() { + String dictionary = + "Dylan,Jacob,Ethan,Gabriel,Nicholas,Jack,Joshua,Caleb,Ryan,Andrew,Caden,Tyler,Michael,Jaden,Zachary," + + "Connor,Logan,Aiden,Noah,Alexande,Jackson,Brayden,Lucas,William,Nathan,Joseph,Justin,Daniel," + + "Benjamin,Christopher,James,Gavin,Evan,Austin,Cameron,Brandon,Mason,Luke,Anthony,Christian," + + "Jonathan,Owen,David,John,Matthew,Samuel,Sean,Hunter,Elijah,Thomas"; + List names = StrUtil.splitTrim(dictionary, ","); + return randomInList(names); + } + + public static String randomGirlFirstName() { + String dictionary = + "Lily,Emily,Sophia,Isabella,Ava,Emma,Kaitlyn,Hannah,Hailey,Olivia,Sarah,Abigail,Madeline,Madison,Kaylee," + + "Ella,Riley,Alexis,Alyssa,Samantha,Lauren,Mia,Grace,Chloe,Ashley,Brianna,Jessica,Elizabeth,Taylor," + + "Makayla,Makenzie,Anna,Zoe,Kayla,Sydney,Megan,Natalie,Kylie,ulia,Avery,Katherine,Isabel,Victoria," + + "Morgan,Kyra,Jasmine,Allison,Savannah,JRachel,Jordan"; + List names = StrUtil.splitTrim(dictionary, ","); + return randomInList(names); + } + + public static String randomIpv4() { + int[][] range = { { 607649792, 608174079 }, // 36.56.0.0-36.63.255.255 + { 1038614528, 1039007743 }, // 61.232.0.0-61.237.255.255 + { 1783627776, 1784676351 }, // 106.80.0.0-106.95.255.255 + { 2035023872, 2035154943 }, // 121.76.0.0-121.77.255.255 + { 2078801920, 2079064063 }, // 123.232.0.0-123.235.255.255 + { -1950089216, -1948778497 }, // 139.196.0.0-139.215.255.255 + { -1425539072, -1425014785 }, // 171.8.0.0-171.15.255.255 + { -1236271104, -1235419137 }, // 182.80.0.0-182.92.255.255 + { -770113536, -768606209 }, // 210.25.0.0-210.47.255.255 + { -569376768, -564133889 }, // 222.16.0.0-222.95.255.255 + }; + + Random rdint = new Random(); + int index = rdint.nextInt(10); + String ip = num2ip(range[index][0] + + new Random().nextInt(range[index][1] - range[index][0])); + return ip; + } + + private static String num2ip(final int ip) { + int[] b = new int[4]; + String result = ""; + b[0] = (ip >> 24) & 0xff; + b[1] = ((ip >> 16) & 0xff); + b[2] = ((ip >> 8) & 0xff); + b[3] = (ip & 0xff); + result = Integer.toString(b[0]) + "." + Integer.toString(b[1]) + "." + + Integer.toString(b[2]) + "." + Integer.toString(b[3]); + return result; + } + + public static String randomLastName() { + String dictionary = + "Smith,Jones,Williams,Taylor,Brown,Davies,Evans,Wilson,Thomas,Johnson,Roberts,Robinson,Thompson,Wright," + + "Walker,White,Edwards,Hughes,Green,Hall,Lewis,Harris,Clarke,Patel,Jackson"; + List names = StrUtil.splitTrim(dictionary, ","); + return randomInList(names); + } + + public static T randomInArray(final T[] list) { + return randomInList(Arrays.asList(list)); + } + + public static T randomInList(final List list) { + if (CollectionUtil.isEmpty(list)) { + return null; + } + int index = randomInt(0, list.size()); + return list.get(index); + } + + public static String randomMac() { + return randomMac(""); + } + + public static String randomMac(final String separator) { + Random random = new Random(); + String[] mac = { String.format("%02x", random.nextInt(0xff)), + String.format("%02x", random.nextInt(0xff)), + String.format("%02x", random.nextInt(0xff)), + String.format("%02x", random.nextInt(0xff)), + String.format("%02x", random.nextInt(0xff)), + String.format("%02x", random.nextInt(0xff)) }; + return String.join(separator, mac); + } + + public static String randomString(final int min, final int max) { + return randomString(WORD_SAMPLE, min, max); + } + + public static String randomNumString(final int min, final int max) { + return randomString(NUMBER_SAMPLE, min, max); + } + + /** + * 使用性能更好的SHA1PRNG, Tomcat的sessionId生成也用此算法. 但JDK7中,需要在启动参数加入 -Djava.security=file:/dev/./urandom (中间那个点很重要) + * 详见:《SecureRandom的江湖偏方与真实效果》http://calvin1978.blogcn.com/articles/securerandom.html + */ + public static SecureRandom secureRandom() { + try { + return SecureRandom.getInstance("SHA1PRNG"); + } catch (NoSuchAlgorithmException e) { + return new SecureRandom(); + } + } + + /** + * 返回无锁的 ThreadLocalRandom + */ + public static ThreadLocalRandom threadLocalRandom() { + return ThreadLocalRandom.current(); + } + +} diff --git a/codes/data/orm/jpa/pom.xml b/codes/data/orm/jpa/pom.xml index 1b7b50f9..572ebf50 100644 --- a/codes/data/orm/jpa/pom.xml +++ b/codes/data/orm/jpa/pom.xml @@ -6,7 +6,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.7 + 2.7.14 io.github.dunwu.spring @@ -34,8 +34,8 @@ lombok
- mysql - mysql-connector-java + com.mysql + mysql-connector-j com.h2database diff --git a/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/User.java b/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/User.java index 9a8430d9..1408f7a6 100644 --- a/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/User.java +++ b/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/User.java @@ -11,6 +11,7 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; +import javax.persistence.Table; /** * 用户实体,对应 user 表 @@ -18,6 +19,7 @@ * @author Zhang Peng * @since 2019-11-18 */ +@Table(name = "t_user") @Entity @Data @ToString diff --git a/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/UserRepository.java b/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/UserRepository.java index 9765129b..cbef53d7 100644 --- a/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/UserRepository.java +++ b/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/UserRepository.java @@ -30,7 +30,7 @@ public interface UserRepository extends JpaRepository { * @param name 用户名 * @return {@link User} */ - User findUserByName(@Param("name") String name); + User findByName(@Param("name") String name); /** * 根据邮箱查找用户 diff --git a/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/UserService.java b/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/UserService.java index b630a7eb..9a696574 100644 --- a/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/UserService.java +++ b/codes/data/orm/jpa/src/main/java/example/spring/data/orm/jpa/UserService.java @@ -92,7 +92,8 @@ public void ok1(User entity) { log.error("create user failed", ex); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); } - log.info("result {} ", userRepository.findUserByName(entity.getName())); + log.info("result {} ", userRepository.findByName(entity.getName())); + log.info("result {} ", userRepository.findByEmail(entity.getEmail())); } /** diff --git a/codes/data/orm/jpa/src/main/resources/sql/data.sql b/codes/data/orm/jpa/src/main/resources/sql/data.sql index 7a73cb7c..7c85077f 100644 --- a/codes/data/orm/jpa/src/main/resources/sql/data.sql +++ b/codes/data/orm/jpa/src/main/resources/sql/data.sql @@ -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, '北京', 'xxx@163.com'); -INSERT INTO `user` (`name`, `age`, `address`, `email`) +INSERT INTO `t_user` (`name`, `age`, `address`, `email`) VALUES ('李四', 19, '上海', 'xxx@163.com'); diff --git a/codes/data/orm/jpa/src/main/resources/sql/schema.sql b/codes/data/orm/jpa/src/main/resources/sql/schema.sql index 8d4c8245..1933a686 100644 --- a/codes/data/orm/jpa/src/main/resources/sql/schema.sql +++ b/codes/data/orm/jpa/src/main/resources/sql/schema.sql @@ -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 '年龄', diff --git a/codes/data/orm/jpa/src/test/java/example/spring/data/orm/jpa/DataJpaTests.java b/codes/data/orm/jpa/src/test/java/example/spring/data/orm/jpa/DataJpaTests.java index 92762a96..d581218e 100644 --- a/codes/data/orm/jpa/src/test/java/example/spring/data/orm/jpa/DataJpaTests.java +++ b/codes/data/orm/jpa/src/test/java/example/spring/data/orm/jpa/DataJpaTests.java @@ -47,9 +47,9 @@ public void insert() { public void batchInsert() { List users = new ArrayList<>(); users.add(new User("张三", 18, "北京", "user1@163.com")); - users.add(new User("李四", 19, "上海", "user1@163.com")); - users.add(new User("王五", 18, "南京", "user1@163.com")); - users.add(new User("赵六", 20, "武汉", "user1@163.com")); + users.add(new User("李四", 19, "上海", "user2@163.com")); + users.add(new User("王五", 18, "南京", "user3@163.com")); + users.add(new User("赵六", 20, "武汉", "user4@163.com")); repository.saveAll(users); long count = repository.count(); @@ -66,13 +66,13 @@ public void batchInsert() { public void delete() { List users = new ArrayList<>(); users.add(new User("张三", 18, "北京", "user1@163.com")); - users.add(new User("李四", 19, "上海", "user1@163.com")); - users.add(new User("王五", 18, "南京", "user1@163.com")); - users.add(new User("赵六", 20, "武汉", "user1@163.com")); + users.add(new User("李四", 19, "上海", "user2@163.com")); + users.add(new User("王五", 18, "南京", "user3@163.com")); + users.add(new User("赵六", 20, "武汉", "user4@163.com")); repository.saveAll(users); repository.deleteByName("张三"); - assertThat(repository.findUserByName("张三")).isNull(); + assertThat(repository.findByName("张三")).isNull(); repository.deleteAll(); List list = repository.findAll(); @@ -83,9 +83,9 @@ public void delete() { public void findAllInPage() { List users = new ArrayList<>(); users.add(new User("张三", 18, "北京", "user1@163.com")); - users.add(new User("李四", 19, "上海", "user1@163.com")); - users.add(new User("王五", 18, "南京", "user1@163.com")); - users.add(new User("赵六", 20, "武汉", "user1@163.com")); + users.add(new User("李四", 19, "上海", "user2@163.com")); + users.add(new User("王五", 18, "南京", "user3@163.com")); + users.add(new User("赵六", 20, "武汉", "user4@163.com")); repository.saveAll(users); PageRequest pageRequest = PageRequest.of(1, 2); @@ -106,7 +106,7 @@ public void update() { oldUser.setName("张三丰"); repository.save(oldUser); - User newUser = repository.findUserByName("张三丰"); + User newUser = repository.findByName("张三丰"); assertThat(newUser).isNotNull(); } diff --git a/codes/data/orm/mybatis-multi-datasource/pom.xml b/codes/data/orm/mybatis-multi-datasource/pom.xml index afca41c7..6d33adb3 100644 --- a/codes/data/orm/mybatis-multi-datasource/pom.xml +++ b/codes/data/orm/mybatis-multi-datasource/pom.xml @@ -7,7 +7,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.7 + 2.7.14 io.github.dunwu.spring @@ -41,8 +41,8 @@ lombok - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.postgresql @@ -52,6 +52,5 @@ com.h2database h2 - diff --git a/codes/data/orm/mybatis-multi-datasource/src/main/java/example/spring/data/orm/mybatis/MybatisMultiDataSourceApplication.java b/codes/data/orm/mybatis-multi-datasource/src/main/java/example/spring/data/orm/mybatis/MybatisMultiDataSourceApplication.java index f4d5083c..dc966bde 100644 --- a/codes/data/orm/mybatis-multi-datasource/src/main/java/example/spring/data/orm/mybatis/MybatisMultiDataSourceApplication.java +++ b/codes/data/orm/mybatis-multi-datasource/src/main/java/example/spring/data/orm/mybatis/MybatisMultiDataSourceApplication.java @@ -3,9 +3,8 @@ import example.spring.data.orm.mybatis.entity.User; import example.spring.data.orm.mybatis.mapper.Db1UserMapper; import example.spring.data.orm.mybatis.mapper.Db2UserMapper; +import lombok.extern.slf4j.Slf4j; import org.mybatis.spring.annotation.MapperScan; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -16,12 +15,11 @@ * @author Zhang Peng * @since 2019-10-12 */ +@Slf4j @SpringBootApplication @MapperScan("example.spring.data.orm.mybatis.mapper") public class MybatisMultiDataSourceApplication implements CommandLineRunner { - private static final Logger log = LoggerFactory.getLogger(MybatisMultiDataSourceApplication.class); - private final Db1UserMapper db1UserMapper; private final Db2UserMapper db2UserMapper; @@ -36,7 +34,7 @@ public static void main(String[] args) { } @Override - public void run(String... args) throws Exception { + public void run(String... args) { if (db1UserMapper == null) { log.error("连接 DB1 数据源失败"); @@ -45,9 +43,6 @@ public void run(String... args) throws Exception { log.info("连接 DB1 数据源成功"); } - db1UserMapper.insert(new User("张三", 21, "南京", "xxx@163.com")); - db1UserMapper.insert(new User("李四", 28, "上海", "xxx@163.com")); - List userList = db1UserMapper.selectList(null); log.info("======= 打印 user 表所有数据 ======="); userList.forEach(user -> { @@ -61,8 +56,6 @@ public void run(String... args) throws Exception { log.info("连接 DB2 数据源成功"); } - db2UserMapper.insert(new User("王五", 24, "北京", "xxx@163.com")); - List userList2 = db2UserMapper.selectList(null); log.info("======= 打印 user 表所有数据 ======="); userList2.forEach(user -> { diff --git a/codes/data/orm/mybatis-multi-datasource/src/main/java/example/spring/data/orm/mybatis/entity/User.java b/codes/data/orm/mybatis-multi-datasource/src/main/java/example/spring/data/orm/mybatis/entity/User.java index 4ac25736..5811ce6b 100644 --- a/codes/data/orm/mybatis-multi-datasource/src/main/java/example/spring/data/orm/mybatis/entity/User.java +++ b/codes/data/orm/mybatis-multi-datasource/src/main/java/example/spring/data/orm/mybatis/entity/User.java @@ -1,24 +1,24 @@ package example.spring.data.orm.mybatis.entity; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.ToString; @Data @ToString +@TableName("`t_user`") public class User { + @TableId(type = IdType.AUTO) private Long id; - private String name; - private Integer age; - private String address; - private String email; - public User() { - } + public User() { } public User(String name, Integer age, String address, String email) { this.name = name; diff --git a/codes/data/orm/mybatis-multi-datasource/src/main/resources/sql/schema.sql b/codes/data/orm/mybatis-multi-datasource/src/main/resources/sql/schema.sql deleted file mode 100644 index 977703b9..00000000 --- a/codes/data/orm/mybatis-multi-datasource/src/main/resources/sql/schema.sql +++ /dev/null @@ -1,13 +0,0 @@ --- ------------------------------------------- --- 运行本项目的 DDL 脚本 --- ------------------------------------------- - --- 创建数据表 user -CREATE TABLE IF NOT EXISTS user ( - id BIGINT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Id', - name VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名', - age TINYINT(3) NOT NULL DEFAULT 0 COMMENT '年龄', - address VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址', - email VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件', - PRIMARY KEY (id) -) COMMENT = '用户表'; diff --git a/codes/data/orm/mybatis-multi-datasource/src/test/java/example/spring/data/orm/mybatis/MybatisMultiDataSourceApplicationTests.java b/codes/data/orm/mybatis-multi-datasource/src/test/java/example/spring/data/orm/mybatis/MybatisMultiDataSourceApplicationTests.java index 6a5c03e0..bee03a4d 100644 --- a/codes/data/orm/mybatis-multi-datasource/src/test/java/example/spring/data/orm/mybatis/MybatisMultiDataSourceApplicationTests.java +++ b/codes/data/orm/mybatis-multi-datasource/src/test/java/example/spring/data/orm/mybatis/MybatisMultiDataSourceApplicationTests.java @@ -33,8 +33,8 @@ public void testDb1() { Long count = db1UserMapper.selectCount(null); Assertions.assertEquals(0, count.intValue()); - db1UserMapper.insert(new User("张三", 21, "南京", "xxx@163.com")); - db1UserMapper.insert(new User("李四", 28, "上海", "xxx@163.com")); + db1UserMapper.insert(new User("王五", 21, "南京", "xxx@163.com")); + db1UserMapper.insert(new User("赵六", 28, "上海", "xxx@163.com")); System.out.println(("----- selectAll method test ------")); List userList = db1UserMapper.selectList(null); diff --git a/codes/data/orm/mybatis-plus/pom.xml b/codes/data/orm/mybatis-plus/pom.xml index f89a1505..2dfb30d8 100644 --- a/codes/data/orm/mybatis-plus/pom.xml +++ b/codes/data/orm/mybatis-plus/pom.xml @@ -7,7 +7,7 @@ org.springframework.boot spring-boot-starter-parent - 2.7.7 + 2.7.14 io.github.dunwu.spring diff --git a/codes/data/orm/mybatis-plus/src/main/java/example/spring/data/orm/mybatis/entity/User.java b/codes/data/orm/mybatis-plus/src/main/java/example/spring/data/orm/mybatis/entity/User.java index dde57a0f..07929877 100644 --- a/codes/data/orm/mybatis-plus/src/main/java/example/spring/data/orm/mybatis/entity/User.java +++ b/codes/data/orm/mybatis-plus/src/main/java/example/spring/data/orm/mybatis/entity/User.java @@ -17,17 +17,17 @@ */ @Data @Accessors(chain = true) -@TableName("`user`") +@TableName("`t_user`") public class User { @TableId(type = IdType.AUTO) private Long id; private String name; private Integer age; + private String address; private String email; @TableField(exist = false) private String ignoreColumn = "ignoreColumn"; - @TableField(exist = false) private Integer count; diff --git a/codes/data/orm/mybatis-plus/src/main/java/example/spring/data/orm/mybatis/entity/User2.java b/codes/data/orm/mybatis-plus/src/main/java/example/spring/data/orm/mybatis/entity/User2.java index 67cadfee..8239b7f3 100644 --- a/codes/data/orm/mybatis-plus/src/main/java/example/spring/data/orm/mybatis/entity/User2.java +++ b/codes/data/orm/mybatis-plus/src/main/java/example/spring/data/orm/mybatis/entity/User2.java @@ -2,6 +2,7 @@ import com.baomidou.mybatisplus.annotation.SqlCondition; import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.experimental.Accessors; import org.apache.ibatis.type.JdbcType; @@ -16,6 +17,7 @@ */ @Data @Accessors(chain = true) +@TableName("`t_user2`") public class User2 { private Long id; diff --git a/codes/data/orm/mybatis-plus/src/main/resources/sql/data-h2.sql b/codes/data/orm/mybatis-plus/src/main/resources/sql/data-h2.sql index 29cf4b52..9990e595 100644 --- a/codes/data/orm/mybatis-plus/src/main/resources/sql/data-h2.sql +++ b/codes/data/orm/mybatis-plus/src/main/resources/sql/data-h2.sql @@ -1,14 +1,13 @@ -DELETE -FROM `user`; - -INSERT INTO `user` (`id`, `name`, `age`, `email`) +DELETE FROM `t_user`; +INSERT INTO `t_user` (`id`, `name`, `age`, `email`) VALUES (1, 'Jone', 18, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com'); -INSERT INTO `user2` (`id`, `name`, `age`) +DELETE FROM `t_user2`; +INSERT INTO `t_user2` (`id`, `name`, `age`) VALUES (1, 'Jone', 18), (2, 'Jack', 20), (3, 'Tom', 28), diff --git a/codes/data/orm/mybatis-plus/src/main/resources/sql/schema-h2.sql b/codes/data/orm/mybatis-plus/src/main/resources/sql/schema-h2.sql index e855fcb8..f7020b1e 100644 --- a/codes/data/orm/mybatis-plus/src/main/resources/sql/schema-h2.sql +++ b/codes/data/orm/mybatis-plus/src/main/resources/sql/schema-h2.sql @@ -1,16 +1,15 @@ -DROP TABLE IF EXISTS `user`; - -CREATE TABLE `user` ( - `id` INT AUTO_INCREMENT NOT NULL COMMENT '主键ID', - `name` VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', - `age` INT NULL DEFAULT NULL COMMENT '年龄', - `email` VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱', +DROP TABLE IF EXISTS `t_user`; +CREATE TABLE `t_user` ( + `id` INT AUTO_INCREMENT NOT NULL COMMENT 'ID', + `name` VARCHAR(255) NULL DEFAULT NULL COMMENT '用户名', + `age` INT NULL DEFAULT NULL COMMENT '年龄', + `address` VARCHAR(255) NULL DEFAULT NULL COMMENT '地址', + `email` VARCHAR(255) NULL DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (`id`) ); -DROP TABLE IF EXISTS `user2`; - -CREATE TABLE `user2` ( +DROP TABLE IF EXISTS `t_user2`; +CREATE TABLE `t_user2` ( `id` INT AUTO_INCREMENT NOT NULL COMMENT '主键ID', `name` VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', `age` INT NULL DEFAULT NULL COMMENT '年龄', diff --git a/codes/data/orm/mybatis-plus/src/test/java/example/spring/data/orm/mybatis/MybatisPlusApplicationTest.java b/codes/data/orm/mybatis-plus/src/test/java/example/spring/data/orm/mybatis/MybatisPlusApplicationTest.java index 630215e6..5fd7bf83 100644 --- a/codes/data/orm/mybatis-plus/src/test/java/example/spring/data/orm/mybatis/MybatisPlusApplicationTest.java +++ b/codes/data/orm/mybatis-plus/src/test/java/example/spring/data/orm/mybatis/MybatisPlusApplicationTest.java @@ -34,6 +34,7 @@ public void aInsert() { user.setName("小羊"); user.setAge(3); user.setEmail("abc@mp.com"); + user.setAddress("内蒙古"); assertThat(mapper.insert(user)).isGreaterThan(0); // 成功直接拿回写的 ID assertThat(user.getId()).isNotNull(); diff --git a/codes/data/orm/mybatis/pom.xml b/codes/data/orm/mybatis/pom.xml index e876b1d6..51a90c04 100644 --- a/codes/data/orm/mybatis/pom.xml +++ b/codes/data/orm/mybatis/pom.xml @@ -9,14 +9,24 @@ jar Spring::数据::ORM::Mybatis + + 1.8 + @ + ${java.version} + ${java.version} + UTF-8 + UTF-8 + + com.alibaba druid + 1.2.18 - mysql - mysql-connector-java + com.mysql + mysql-connector-j @@ -35,14 +45,17 @@ org.mybatis mybatis + 3.5.10 org.mybatis mybatis-spring + 2.0.7 org.mybatis.generator mybatis-generator-core + 1.4.2 @@ -57,7 +70,6 @@ org.springframework spring-context-support - org.springframework.boot spring-boot-starter-test @@ -68,9 +80,9 @@ - io.github.dunwu - dunwu-dependencies - 1.1.0 + org.springframework.boot + spring-boot-dependencies + 2.7.14 pom import diff --git a/codes/data/orm/mybatis/src/main/java/example/spring/data/orm/mybatis/MybatisDemo.java b/codes/data/orm/mybatis/src/main/java/example/spring/data/orm/mybatis/MybatisDemo.java index 0e70d5d8..820e5bf9 100644 --- a/codes/data/orm/mybatis/src/main/java/example/spring/data/orm/mybatis/MybatisDemo.java +++ b/codes/data/orm/mybatis/src/main/java/example/spring/data/orm/mybatis/MybatisDemo.java @@ -30,7 +30,7 @@ public static void main(String[] args) throws Exception { // 3. 使用SqlSession查询 Long params = 1L; List list = - sqlSession.selectList("io.github.dunwu.spring.orm.mapper.UserMapper.selectByPrimaryKey", params); + sqlSession.selectList("example.spring.data.orm.mybatis.mapper.UserMapper.selectByPrimaryKey", params); for (User user : list) { System.out.println("user name: " + user.getName()); } diff --git a/codes/data/orm/mybatis/src/main/resources/mybatis/mybatis-spring.xml b/codes/data/orm/mybatis/src/main/resources/mybatis/mybatis-spring.xml index 2e50e67d..e372fb85 100644 --- a/codes/data/orm/mybatis/src/main/resources/mybatis/mybatis-spring.xml +++ b/codes/data/orm/mybatis/src/main/resources/mybatis/mybatis-spring.xml @@ -52,7 +52,7 @@ - +