feat: 修改数据篇示例代码
This commit is contained in:
parent
b21825b4cd
commit
85d8e22556
|
@ -19,7 +19,7 @@ insert_final_newline = true
|
|||
[*.{bat, cmd}]
|
||||
end_of_line = crlf
|
||||
|
||||
[*.{java, gradle, groovy, kt, sh, xml}]
|
||||
[*.{java, gradle, groovy, kt, sh}]
|
||||
indent_size = 4
|
||||
|
||||
[*.md]
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
author.name = Zhang Peng
|
||||
throw.exception = false
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
|
|
@ -26,7 +26,7 @@ CREATE DATABASE spring_boot_tutorial;
|
|||
> 注意:Mysql8 和 Mysql5 客户端驱动的驱动类是不同的。
|
||||
|
||||
```properties
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
@ -51,7 +51,7 @@ java -jar spring-boot-data-jdbc-1.0.0.jar
|
|||
|
||||
```java
|
||||
... ...
|
||||
18:11:21.895 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.printDataSourceInfo - DataSource Url: jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
18:11:21.895 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.printDataSourceInfo - DataSource Url: jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
18:11:21.896 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.run - Connect to datasource success.
|
||||
18:11:21.960 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.lambda$run$0 - User(id=1, username=admin, password=$2a$10$Y9uV9YjFuNlATDGz5MeTZeuo8LbebbpP6jRgtZYQcgiCZRlf8rJYG, email=admin@xxx.com)
|
||||
18:11:21.960 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.lambda$run$0 - User(id=2, username=user, password=$2a$10$Y9uV9YjFuNlATDGz5MeTZeuo8LbebbpP6jRgtZYQcgiCZRlf8rJYG, email=user@xxx.com)
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
|
|
@ -31,7 +31,7 @@ CREATE DATABASE spring_boot_tutorial;
|
|||
|
||||
```properties
|
||||
# datasource01
|
||||
spring.datasource.mysql.jdbc-url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.mysql.jdbc-url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.mysql.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.mysql.username = root
|
||||
spring.datasource.mysql.password = root
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.2.1.RELEASE</version>
|
||||
<version>2.7.3</version>
|
||||
</parent>
|
||||
|
||||
<groupId>io.github.dunwu.spring</groupId>
|
||||
|
@ -16,7 +16,7 @@
|
|||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
<artifactId>spring-boot-starter-data-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
|
|
@ -1,12 +1,15 @@
|
|||
package io.github.dunwu.springboot.data;
|
||||
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
|
@ -26,6 +29,15 @@ public class DataSourceConfig {
|
|||
return new JdbcTemplate(dataSource);
|
||||
}
|
||||
|
||||
@Primary
|
||||
@Bean("mysqlTransactionManager")
|
||||
public DataSourceTransactionManager mysqlTransactionManager(@Qualifier("mysqlDataSource") DataSource dataSource,
|
||||
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
|
||||
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
|
||||
transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(transactionManager));
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
@Bean("h2DataSource")
|
||||
@ConfigurationProperties(prefix = "spring.datasource.h2")
|
||||
public DataSource h2DataSource() {
|
||||
|
@ -37,4 +49,12 @@ public class DataSourceConfig {
|
|||
return new JdbcTemplate(dataSource);
|
||||
}
|
||||
|
||||
@Bean("h2TransactionManager")
|
||||
public DataSourceTransactionManager h2TransactionManager(@Qualifier("h2DataSource") DataSource dataSource,
|
||||
ObjectProvider<TransactionManagerCustomizers> transactionManagerCustomizers) {
|
||||
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
|
||||
transactionManagerCustomizers.ifAvailable((customizers) -> customizers.customize(transactionManager));
|
||||
return transactionManager;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -27,14 +27,14 @@ public class H2UserDaoImpl implements UserDao {
|
|||
|
||||
@Override
|
||||
public void insert(User user) {
|
||||
jdbcTemplate.update("INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)",
|
||||
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<User> users) {
|
||||
String sql = "INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)";
|
||||
String sql = "INSERT INTO `user`(`name`, `age`, `address`, `email`) VALUES(?, ?, ?, ?)";
|
||||
|
||||
List<Object[]> params = new ArrayList<>();
|
||||
|
||||
|
@ -46,25 +46,25 @@ public class H2UserDaoImpl implements UserDao {
|
|||
|
||||
@Override
|
||||
public void deleteByName(String name) {
|
||||
jdbcTemplate.update("DELETE FROM user WHERE name = ?", name);
|
||||
jdbcTemplate.update("DELETE FROM `user` WHERE name = ?", name);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteAll() {
|
||||
jdbcTemplate.execute("DELETE FROM user");
|
||||
jdbcTemplate.execute("DELETE FROM `user`");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(User user) {
|
||||
jdbcTemplate.update("UPDATE user SET name=?, age=?, address=?, email=? WHERE id=?",
|
||||
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);
|
||||
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM `user`", Integer.class);
|
||||
} catch (EmptyResultDataAccessException e) {
|
||||
return null;
|
||||
}
|
||||
|
@ -72,13 +72,13 @@ public class H2UserDaoImpl implements UserDao {
|
|||
|
||||
@Override
|
||||
public List<User> list() {
|
||||
return jdbcTemplate.query("SELECT * FROM user", new BeanPropertyRowMapper<>(User.class));
|
||||
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 = ?",
|
||||
return jdbcTemplate.queryForObject("SELECT * FROM `user` WHERE name = ?",
|
||||
new BeanPropertyRowMapper<>(User.class), name);
|
||||
} catch (EmptyResultDataAccessException e) {
|
||||
return null;
|
||||
|
@ -92,22 +92,22 @@ public class H2UserDaoImpl implements UserDao {
|
|||
|
||||
@Override
|
||||
public void truncate() {
|
||||
jdbcTemplate.execute("TRUNCATE TABLE user");
|
||||
jdbcTemplate.execute("TRUNCATE TABLE `user`");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void recreateTable() {
|
||||
jdbcTemplate.execute("DROP TABLE IF EXISTS user");
|
||||
jdbcTemplate.execute("DROP TABLE IF EXISTS `user`;");
|
||||
|
||||
String sqlStatement =
|
||||
"CREATE TABLE user (\n"
|
||||
+ " id INT(20) 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 `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);
|
||||
}
|
||||
|
|
|
@ -1,10 +1,14 @@
|
|||
# datasource01
|
||||
spring.datasource.mysql.jdbc-url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
# 数据源一:Mysql
|
||||
spring.datasource.mysql.jdbc-url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.mysql.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.mysql.username = root
|
||||
spring.datasource.mysql.password = root
|
||||
# datasource02
|
||||
# 数据源一:H2
|
||||
spring.datasource.h2.jdbc-url = jdbc:h2:mem:test
|
||||
spring.datasource.h2.driver-class-name = org.h2.Driver
|
||||
spring.datasource.h2.username = sa
|
||||
spring.datasource.h2.password =
|
||||
# 强制每次启动使用 sql 初始化数据,本项目仅为了演示方便,真实环境应避免这种模式
|
||||
spring.sql.init.mode = always
|
||||
spring.sql.init.schema-locations = classpath:sql/schema.sql
|
||||
spring.sql.init.data-locations = classpath:sql/data.sql
|
||||
|
|
|
@ -5,13 +5,13 @@
|
|||
-- -------------------------------------------------------------------
|
||||
|
||||
-- 创建用户表
|
||||
DROP TABLE IF EXISTS user;
|
||||
CREATE TABLE user (
|
||||
id INT(20) NOT NULL AUTO_INCREMENT COMMENT 'ID',
|
||||
name VARCHAR(255) NOT NULL DEFAULT '' COMMENT '用户名',
|
||||
age INT(3) NOT NULL DEFAULT 0 COMMENT '年龄',
|
||||
address VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址',
|
||||
email VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE (name)
|
||||
)
|
||||
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`)
|
||||
);
|
||||
|
|
|
@ -5,14 +5,13 @@
|
|||
-- -------------------------------------------------------------------
|
||||
|
||||
-- 创建用户表
|
||||
DROP TABLE IF EXISTS user;
|
||||
CREATE TABLE 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 '年龄',
|
||||
address VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址',
|
||||
email VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE (name)
|
||||
);
|
||||
|
||||
DROP TABLE IF EXISTS `user`;
|
||||
CREATE TABLE `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 '年龄',
|
||||
`address` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址',
|
||||
`email` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE (`name`)
|
||||
) COMMENT = '用户表';
|
||||
|
|
|
@ -1,15 +1,13 @@
|
|||
package io.github.dunwu.springboot.data;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.Rollback;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
@ -17,7 +15,6 @@ import java.util.List;
|
|||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@Rollback
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = { SpringBootDataJdbcMultiDataSourceApplication.class })
|
||||
public class DataJdbcH2DataSourceTest {
|
||||
|
||||
|
@ -27,7 +24,7 @@ public class DataJdbcH2DataSourceTest {
|
|||
@Qualifier("h2UserDao")
|
||||
private UserDao userDAO;
|
||||
|
||||
@Before
|
||||
@BeforeEach
|
||||
public void before() {
|
||||
userDAO.recreateTable();
|
||||
}
|
||||
|
|
|
@ -1,33 +1,28 @@
|
|||
package io.github.dunwu.springboot.data;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.annotation.Rollback;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@Slf4j
|
||||
@Rollback
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = { SpringBootDataJdbcMultiDataSourceApplication.class })
|
||||
public class DataJdbcMysqlDataSourceTest {
|
||||
|
||||
private final Logger log = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
@Autowired
|
||||
@Qualifier("mysqlUserDao")
|
||||
private UserDao userDAO;
|
||||
|
||||
@Before
|
||||
@BeforeEach
|
||||
public void before() {
|
||||
userDAO.recreateTable();
|
||||
}
|
||||
|
|
|
@ -26,7 +26,7 @@ CREATE DATABASE spring_boot_tutorial;
|
|||
> 注意:Mysql8 和 Mysql5 客户端驱动的驱动类是不同的。
|
||||
|
||||
```properties
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
@ -51,7 +51,7 @@ java -jar spring-boot-data-jdbc-1.0.0.jar
|
|||
|
||||
```java
|
||||
... ...
|
||||
18:11:21.895 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.printDataSourceInfo - DataSource Url: jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
18:11:21.895 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.printDataSourceInfo - DataSource Url: jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
18:11:21.896 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.run - Connect to datasource success.
|
||||
18:11:21.960 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.lambda$run$0 - User(id=1, username=admin, password=$2a$10$Y9uV9YjFuNlATDGz5MeTZeuo8LbebbpP6jRgtZYQcgiCZRlf8rJYG, email=admin@xxx.com)
|
||||
18:11:21.960 [main] [INFO ] i.g.d.s.SpringBootDataJdbcApplication$$EnhancerBySpringCGLIB$$605038c2.lambda$run$0 - User(id=2, username=user, password=$2a$10$Y9uV9YjFuNlATDGz5MeTZeuo8LbebbpP6jRgtZYQcgiCZRlf8rJYG, email=user@xxx.com)
|
||||
|
@ -64,8 +64,4 @@ java -jar spring-boot-data-jdbc-1.0.0.jar
|
|||
|
||||
### 单元测试
|
||||
|
||||
执行 `SpringBootDataJdbcTest` 可以更直观的看到 JDBC 模式下的 CRUD 操作。
|
||||
|
||||
## 扩展学习
|
||||
|
||||
- [Mysql 教程](https://dunwu.github.io/db-tutorial/#/sql/mysql/README)
|
||||
执行 `SpringBootDataJdbcTest` 可以更直观的看到 JDBC 模式下的 CRUD 操作。``
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.2.1.RELEASE</version>
|
||||
<version>2.7.3</version>
|
||||
</parent>
|
||||
|
||||
<groupId>io.github.dunwu.spring</groupId>
|
||||
|
@ -16,7 +16,7 @@
|
|||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
<artifactId>spring-boot-starter-data-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
# 强制每次启动使用 sql 初始化数据,本项目仅为了演示方便,真实环境应避免这种模式
|
||||
spring.datasource.initialization-mode = ALWAYS
|
||||
spring.datasource.schema = classpath:sql/schema.sql
|
||||
spring.datasource.data = classpath:sql/data.sql
|
||||
spring.sql.init.mode = always
|
||||
spring.sql.init.schema-locations = classpath:sql/schema.sql
|
||||
spring.sql.init.data-locations = classpath:sql/data.sql
|
||||
|
|
|
@ -5,14 +5,13 @@
|
|||
-- -------------------------------------------------------------------
|
||||
|
||||
-- 创建用户表
|
||||
DROP TABLE IF EXISTS user;
|
||||
CREATE TABLE 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 '年龄',
|
||||
address VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址',
|
||||
email VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE (name)
|
||||
);
|
||||
|
||||
DROP TABLE IF EXISTS `user`;
|
||||
CREATE TABLE `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 '年龄',
|
||||
`address` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '地址',
|
||||
`email` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '邮件',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE (`name`)
|
||||
) COMMENT = '用户表';
|
||||
|
|
|
@ -1,31 +1,26 @@
|
|||
package io.github.dunwu.springboot.data;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@Slf4j
|
||||
@Rollback
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = { SpringBootDataJdbcApplication.class })
|
||||
public class SpringBootDataJdbcTest {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SpringBootDataJdbcTest.class);
|
||||
public class DataJdbcMysqlDataSourceTest {
|
||||
|
||||
@Autowired
|
||||
private UserDao userDAO;
|
||||
|
||||
@Before
|
||||
@BeforeEach
|
||||
public void before() {
|
||||
userDAO.truncate();
|
||||
}
|
|
@ -26,7 +26,7 @@ CREATE DATABASE spring_boot_tutorial;
|
|||
> 注意:Mysql8 和 Mysql5 客户端驱动的驱动类是不同的。
|
||||
|
||||
```properties
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
@ -51,7 +51,7 @@ java -jar spring-boot-data-jpa-1.0.0.jar
|
|||
|
||||
```java
|
||||
... ...
|
||||
20:22:33.401 [main] [INFO ] i.g.d.s.SpringBootDataJpaApplication$$EnhancerBySpringCGLIB$$a0a040c6.printDataSourceInfo - DataSource Url: jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
20:22:33.401 [main] [INFO ] i.g.d.s.SpringBootDataJpaApplication$$EnhancerBySpringCGLIB$$a0a040c6.printDataSourceInfo - DataSource Url: jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
20:22:33.402 [main] [INFO ] i.g.d.s.SpringBootDataJpaApplication$$EnhancerBySpringCGLIB$$a0a040c6.run - Connect to datasource success.
|
||||
... ...
|
||||
```
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
server.port = 8080
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
|
|
@ -7,7 +7,7 @@
|
|||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.2.1.RELEASE</version>
|
||||
<version>2.7.3</version>
|
||||
</parent>
|
||||
|
||||
<groupId>io.github.dunwu.spring</groupId>
|
||||
|
@ -16,8 +16,9 @@
|
|||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<version>3.5.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
|
@ -29,18 +30,13 @@
|
|||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<groupId>p6spy</groupId>
|
||||
<artifactId>p6spy</artifactId>
|
||||
<version>3.9.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baomidou</groupId>
|
||||
<artifactId>mybatis-plus-boot-starter</artifactId>
|
||||
<version>3.1.2</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
|
|
|
@ -32,7 +32,7 @@ public class SpringBootDataMybatisPlusApplication implements CommandLineRunner {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
public void run(String... args) {
|
||||
|
||||
if (userMapper == null) {
|
||||
log.error("连接数据源失败");
|
||||
|
|
|
@ -1,30 +1,34 @@
|
|||
package io.github.dunwu.springboot.data.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
import lombok.ToString;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 用户实体对应表 user
|
||||
* </p>
|
||||
*
|
||||
* @author hubin
|
||||
* @since 2018-08-11
|
||||
*/
|
||||
@Data
|
||||
@ToString
|
||||
@Accessors(chain = true)
|
||||
@TableName("`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";
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String name, Integer age, String address, String email) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
this.address = address;
|
||||
this.email = email;
|
||||
}
|
||||
@TableField(exist = false)
|
||||
private Integer count;
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,26 @@
|
|||
package io.github.dunwu.springboot.data.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.SqlCondition;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import lombok.Data;
|
||||
import lombok.experimental.Accessors;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 用户实体对应表 user2 测试注解条件
|
||||
* </p>
|
||||
*
|
||||
* @author hubin
|
||||
* @since 2021-08-19
|
||||
*/
|
||||
@Data
|
||||
@Accessors(chain = true)
|
||||
public class User2 {
|
||||
|
||||
private Long id;
|
||||
@TableField(condition = SqlCondition.LIKE, jdbcType = JdbcType.VARCHAR)
|
||||
private String name;
|
||||
private Integer age;
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
package io.github.dunwu.springboot.data.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import io.github.dunwu.springboot.data.entity.User2;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* MP 支持不需要 UserMapper.xml 测试注解条件
|
||||
* </p>
|
||||
*
|
||||
* @author hubin
|
||||
* @since 2021-08-19
|
||||
*/
|
||||
public interface User2Mapper extends BaseMapper<User2> {
|
||||
|
||||
}
|
|
@ -3,6 +3,14 @@ package io.github.dunwu.springboot.data.mapper;
|
|||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import io.github.dunwu.springboot.data.entity.User;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* MP 支持不需要 UserMapper.xml 这个模块演示内置 CRUD 咱们就不要 XML 部分了
|
||||
* </p>
|
||||
*
|
||||
* @author hubin
|
||||
* @since 2018-08-11
|
||||
*/
|
||||
public interface UserMapper extends BaseMapper<User> {
|
||||
|
||||
}
|
||||
|
|
|
@ -1,9 +1,8 @@
|
|||
server.port = 8080
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
spring.datasource.url = jdbc:p6spy:h2:mem:test
|
||||
spring.datasource.driver-class-name = com.p6spy.engine.spy.P6SpyDriver
|
||||
spring.datasource.username = sa
|
||||
spring.datasource.password =
|
||||
# 强制每次启动使用 sql 初始化数据,本项目仅为了演示方便,真实环境应避免这种模式
|
||||
spring.datasource.initialization-mode = ALWAYS
|
||||
spring.datasource.schema = classpath:sql/schema.sql
|
||||
spring.datasource.data = classpath:sql/data.sql
|
||||
spring.sql.init.mode = always
|
||||
spring.sql.init.schema-locations = classpath:sql/schema-h2.sql
|
||||
spring.sql.init.data-locations = classpath:sql/data-h2.sql
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
|
||||
# 自定义日志打印
|
||||
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
|
||||
#日志输出到控制台
|
||||
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
|
||||
# 使用日志系统记录 sql
|
||||
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
|
||||
# 设置 p6spy driver 代理
|
||||
deregisterdrivers=true
|
||||
# 取消JDBC URL前缀
|
||||
useprefix=true
|
||||
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
|
||||
excludecategories=info,debug,result,commit,resultset
|
||||
# 日期格式
|
||||
dateformat=yyyy-MM-dd HH:mm:ss
|
||||
# 实际驱动可多个
|
||||
#driverlist=org.h2.Driver
|
||||
# 是否开启慢SQL记录
|
||||
outagedetection=true
|
||||
# 慢SQL记录标准 2 秒
|
||||
outagedetectioninterval=2
|
|
@ -0,0 +1,16 @@
|
|||
DELETE
|
||||
FROM `user`;
|
||||
|
||||
INSERT INTO `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`)
|
||||
VALUES (1, 'Jone', 18),
|
||||
(2, 'Jack', 20),
|
||||
(3, 'Tom', 28),
|
||||
(4, 'Sandy', 21),
|
||||
(5, 'Billie', 24);
|
|
@ -1,8 +0,0 @@
|
|||
-- -------------------------------------------
|
||||
-- 运行本项目的 DML 脚本
|
||||
-- -------------------------------------------
|
||||
|
||||
INSERT INTO user (name, age, address, email)
|
||||
VALUES ('张三', 18, '北京', 'xxx@163.com');
|
||||
INSERT INTO user (name, age, address, email)
|
||||
VALUES ('李四', 19, '上海', 'xxx@163.com');
|
|
@ -0,0 +1,18 @@
|
|||
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 '邮箱',
|
||||
PRIMARY KEY (`id`)
|
||||
);
|
||||
|
||||
DROP TABLE IF EXISTS `user2`;
|
||||
|
||||
CREATE TABLE `user2` (
|
||||
`id` INT AUTO_INCREMENT NOT NULL COMMENT '主键ID',
|
||||
`name` VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
|
||||
`age` INT NULL DEFAULT NULL COMMENT '年龄',
|
||||
PRIMARY KEY (`id`)
|
||||
);
|
|
@ -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 = '用户表';
|
|
@ -1,31 +1,224 @@
|
|||
package io.github.dunwu.springboot.data;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import io.github.dunwu.springboot.data.entity.User;
|
||||
import io.github.dunwu.springboot.data.entity.User2;
|
||||
import io.github.dunwu.springboot.data.mapper.User2Mapper;
|
||||
import io.github.dunwu.springboot.data.mapper.UserMapper;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles({ "test" })
|
||||
@RunWith(SpringRunner.class)
|
||||
public class SpringBootDataMybatisPlusApplicationTest {
|
||||
|
||||
@Autowired
|
||||
private UserMapper userMapper;
|
||||
@Resource
|
||||
private UserMapper mapper;
|
||||
@Resource
|
||||
private User2Mapper user2Mapper;
|
||||
|
||||
@Test
|
||||
public void testSelect() {
|
||||
System.out.println(("----- selectAll method test ------"));
|
||||
List<User> userList = userMapper.selectList(null);
|
||||
Assert.assertEquals(2, userList.size());
|
||||
userList.forEach(System.out::println);
|
||||
public void aInsert() {
|
||||
User user = new User();
|
||||
user.setId(6L);
|
||||
user.setName("小羊");
|
||||
user.setAge(3);
|
||||
user.setEmail("abc@mp.com");
|
||||
assertThat(mapper.insert(user)).isGreaterThan(0);
|
||||
// 成功直接拿回写的 ID
|
||||
assertThat(user.getId()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bDelete() {
|
||||
assertThat(mapper.deleteById(3L)).isGreaterThan(0);
|
||||
assertThat(mapper.delete(new QueryWrapper<User>()
|
||||
.lambda().eq(User::getName, "Sandy"))).isGreaterThan(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void cUpdate() {
|
||||
assertThat(mapper.updateById(new User().setId(1L).setEmail("ab@c.c"))).isGreaterThan(0);
|
||||
assertThat(
|
||||
mapper.update(
|
||||
new User().setName("mp"),
|
||||
Wrappers.<User>lambdaUpdate()
|
||||
.set(User::getAge, 3)
|
||||
.eq(User::getId, 2)
|
||||
)
|
||||
).isGreaterThan(0);
|
||||
User user = mapper.selectById(2);
|
||||
assertThat(user.getAge()).isEqualTo(3);
|
||||
assertThat(user.getName()).isEqualTo("mp");
|
||||
|
||||
mapper.update(
|
||||
null,
|
||||
Wrappers.<User>lambdaUpdate().set(User::getEmail, null).eq(User::getId, 2)
|
||||
);
|
||||
assertThat(mapper.selectById(1).getEmail()).isEqualTo("ab@c.c");
|
||||
user = mapper.selectById(2);
|
||||
assertThat(user.getEmail()).isNull();
|
||||
assertThat(user.getName()).isEqualTo("mp");
|
||||
|
||||
mapper.update(
|
||||
new User().setEmail("miemie@baomidou.com"),
|
||||
new QueryWrapper<User>()
|
||||
.lambda().eq(User::getId, 2)
|
||||
);
|
||||
user = mapper.selectById(2);
|
||||
assertThat(user.getEmail()).isEqualTo("miemie@baomidou.com");
|
||||
|
||||
mapper.update(
|
||||
new User().setEmail("miemie2@baomidou.com"),
|
||||
Wrappers.<User>lambdaUpdate()
|
||||
.set(User::getAge, null)
|
||||
.eq(User::getId, 2)
|
||||
);
|
||||
user = mapper.selectById(2);
|
||||
assertThat(user.getEmail()).isEqualTo("miemie2@baomidou.com");
|
||||
assertThat(user.getAge()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void dSelect() {
|
||||
mapper.insert(
|
||||
new User().setId(10086L)
|
||||
.setName("miemie")
|
||||
.setEmail("miemie@baomidou.com")
|
||||
.setAge(3));
|
||||
assertThat(mapper.selectById(10086L).getEmail()).isEqualTo("miemie@baomidou.com");
|
||||
User user = mapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getId, 10086));
|
||||
assertThat(user.getName()).isEqualTo("miemie");
|
||||
assertThat(user.getAge()).isEqualTo(3);
|
||||
|
||||
mapper.selectList(Wrappers.<User>lambdaQuery().select(User::getId))
|
||||
.forEach(x -> {
|
||||
assertThat(x.getId()).isNotNull();
|
||||
assertThat(x.getEmail()).isNull();
|
||||
assertThat(x.getName()).isNull();
|
||||
assertThat(x.getAge()).isNull();
|
||||
});
|
||||
mapper.selectList(new QueryWrapper<User>().select("id", "name"))
|
||||
.forEach(x -> {
|
||||
assertThat(x.getId()).isNotNull();
|
||||
assertThat(x.getEmail()).isNull();
|
||||
assertThat(x.getName()).isNotNull();
|
||||
assertThat(x.getAge()).isNull();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderBy() {
|
||||
List<User> users = mapper.selectList(Wrappers.<User>query().orderByAsc("age"));
|
||||
assertThat(users).isNotEmpty();
|
||||
//多字段排序
|
||||
List<User> users2 = mapper.selectList(Wrappers.<User>query().orderByAsc("age", "name"));
|
||||
assertThat(users2).isNotEmpty();
|
||||
//先按age升序排列,age相同再按name降序排列
|
||||
List<User> users3 = mapper.selectList(Wrappers.<User>query().orderByAsc("age").orderByDesc("name"));
|
||||
assertThat(users3).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void selectMaps() {
|
||||
List<Map<String, Object>> mapList = mapper.selectMaps(Wrappers.<User>query().orderByAsc("age"));
|
||||
assertThat(mapList).isNotEmpty();
|
||||
assertThat(mapList.get(0)).isNotEmpty();
|
||||
System.out.println(mapList.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void selectMapsPage() {
|
||||
IPage<Map<String, Object>> page =
|
||||
mapper.selectMapsPage(new Page<>(1, 5), Wrappers.<User>query().orderByAsc("age"));
|
||||
assertThat(page).isNotNull();
|
||||
assertThat(page.getRecords()).isNotEmpty();
|
||||
assertThat(page.getRecords().get(0)).isNotEmpty();
|
||||
System.out.println(page.getRecords().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void orderByLambda() {
|
||||
List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().orderByAsc(User::getAge));
|
||||
assertThat(users).isNotEmpty();
|
||||
//多字段排序
|
||||
List<User> users2 = mapper.selectList(Wrappers.<User>lambdaQuery().orderByAsc(User::getAge, User::getName));
|
||||
assertThat(users2).isNotEmpty();
|
||||
//先按age升序排列,age相同再按name降序排列
|
||||
List<User> users3 =
|
||||
mapper.selectList(Wrappers.<User>lambdaQuery().orderByAsc(User::getAge).orderByDesc(User::getName));
|
||||
assertThat(users3).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectMaxId() {
|
||||
QueryWrapper<User> wrapper = new QueryWrapper<>();
|
||||
wrapper.select("max(id) as id");
|
||||
User user = mapper.selectOne(wrapper);
|
||||
System.out.println("maxId=" + user.getId());
|
||||
List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().orderByDesc(User::getId));
|
||||
assertThat(user.getId().longValue()).isEqualTo(users.get(0).getId().longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGroup() {
|
||||
QueryWrapper<User> wrapper = new QueryWrapper<>();
|
||||
wrapper.select("age, count(*)")
|
||||
.groupBy("age");
|
||||
List<Map<String, Object>> maplist = mapper.selectMaps(wrapper);
|
||||
for (Map<String, Object> mp : maplist) {
|
||||
System.out.println(mp);
|
||||
}
|
||||
/**
|
||||
* lambdaQueryWrapper groupBy orderBy
|
||||
*/
|
||||
LambdaQueryWrapper<User> lambdaQueryWrapper = new QueryWrapper<User>().lambda()
|
||||
.select(User::getAge)
|
||||
.groupBy(User::getAge)
|
||||
.orderByAsc(User::getAge);
|
||||
for (User user : mapper.selectList(lambdaQueryWrapper)) {
|
||||
System.out.println(user);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTableFieldExistFalse() {
|
||||
QueryWrapper<User> wrapper = new QueryWrapper<>();
|
||||
wrapper.select("age, count(age) as count")
|
||||
.groupBy("age");
|
||||
List<User> list = mapper.selectList(wrapper);
|
||||
list.forEach(System.out::println);
|
||||
list.forEach(x -> {
|
||||
Assertions.assertNull(x.getId());
|
||||
Assertions.assertNotNull(x.getAge());
|
||||
Assertions.assertNotNull(x.getCount());
|
||||
});
|
||||
mapper.insert(
|
||||
new User().setId(10088L)
|
||||
.setName("miemie")
|
||||
.setEmail("miemie@baomidou.com")
|
||||
.setAge(3));
|
||||
User miemie = mapper.selectById(10088L);
|
||||
Assertions.assertNotNull(miemie);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSqlCondition() {
|
||||
Assertions.assertEquals(user2Mapper.selectList(Wrappers.<User2>query()
|
||||
.setEntity(new User2().setName("n"))).size(), 2);
|
||||
Assertions.assertEquals(user2Mapper.selectList(Wrappers.<User2>query().like("name", "J")).size(), 2);
|
||||
Assertions.assertEquals(user2Mapper.selectList(Wrappers.<User2>query().gt("age", 18)
|
||||
.setEntity(new User2().setName("J"))).size(), 1);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,6 +0,0 @@
|
|||
spring.datasource.url = jdbc:h2:mem:test
|
||||
spring.datasource.driver-class-name = org.h2.Driver
|
||||
spring.datasource.username = sa
|
||||
spring.datasource.password =
|
||||
spring.datasource.schema = classpath:sql/schema-h2.sql
|
||||
spring.datasource.data = classpath:sql/data-h2.sql
|
|
@ -1,10 +0,0 @@
|
|||
-- -------------------------------------------------------------------
|
||||
-- 运行本项目的初始化 DML 脚本(H2 SQL)
|
||||
-- H2 知识点可以参考:
|
||||
-- https://dunwu.github.io/db-tutorial/#/sql/h2
|
||||
-- -------------------------------------------------------------------
|
||||
|
||||
INSERT INTO user (name, age, address, email)
|
||||
VALUES ('张三', 18, '北京', 'xxx@163.com');
|
||||
INSERT INTO user (name, age, address, email)
|
||||
VALUES ('李四', 19, '上海', 'xxx@163.com');
|
|
@ -1,16 +0,0 @@
|
|||
-- -------------------------------------------------------------------
|
||||
-- 运行本项目的初始化 DDL 脚本(H2 SQL)
|
||||
-- H2 知识点可以参考:
|
||||
-- https://dunwu.github.io/db-tutorial/#/sql/h2
|
||||
-- -------------------------------------------------------------------
|
||||
|
||||
-- 强制新建用户表
|
||||
DROP TABLE IF EXISTS user;
|
||||
CREATE TABLE user (
|
||||
id INT IDENTITY NOT NULL 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)
|
||||
);
|
|
@ -14,10 +14,10 @@
|
|||
<packaging>jar</packaging>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>io.github.dunwu.spring</groupId>
|
||||
<artifactId>spring-common</artifactId>
|
||||
</dependency>
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>io.github.dunwu.spring</groupId>-->
|
||||
<!-- <artifactId>spring-common</artifactId>-->
|
||||
<!-- </dependency>-->
|
||||
|
||||
<!-- db start -->
|
||||
<dependency>
|
||||
|
@ -83,5 +83,9 @@
|
|||
</dependency>
|
||||
<!-- spring data end -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.url = jdbc:mysql://localhost:3306/spring_tutorial?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
|
||||
spring.datasource.username = root
|
||||
spring.datasource.password = root
|
||||
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
|
||||
|
|
Loading…
Reference in New Issue