feat: 更新示例代码

pull/13/head
dunwu 2022-01-10 10:15:31 +08:00
parent 0b97adce78
commit 16a41f1520
27 changed files with 761 additions and 439 deletions

View File

@ -14,7 +14,7 @@
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<junit.version>4.12</junit.version>
<junit.version>4.13.1</junit.version>
</properties>
<dependencies>
@ -39,7 +39,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<version>2.0.206</version>
<scope>test</scope>
</dependency>
<!-- database end -->

View File

@ -15,7 +15,7 @@
<maven.compiler.target>${java.version}</maven.compiler.target>
<hbase.version>1.3.1</hbase.version>
<junit.version>4.12</junit.version>
<junit.version>4.13.1</junit.version>
<dunwu.version>0.5.7</dunwu.version>
</properties>

View File

@ -15,111 +15,32 @@
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<spring.version>4.3.13.RELEASE</spring.version>
<logback.version>1.2.3</logback.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- db begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- db end -->
<!-- log start -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<!-- log end -->
<!-- spring begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<!-- spring end -->
<!-- test begin -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<!-- test end -->
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>${spring.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- database begin -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<!-- database end -->
<!-- log begin -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-parent</artifactId>
<version>${logback.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- log end -->
<!-- test begin -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- test end -->
</dependencies>
</dependencyManagement>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>logback.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,45 @@
package io.github.dunwu.javadb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.Connection;
import javax.sql.DataSource;
@Slf4j
@SpringBootApplication
public class SpringBootDataJdbcApplication implements CommandLineRunner {
private final JdbcTemplate jdbcTemplate;
public SpringBootDataJdbcApplication(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public static void main(String[] args) {
SpringApplication.run(SpringBootDataJdbcApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
DataSource dataSource = jdbcTemplate.getDataSource();
Connection connection;
if (dataSource != null) {
connection = dataSource.getConnection();
} else {
log.error("连接数据源失败!");
return;
}
if (connection != null) {
log.info("数据源 Url: {}", connection.getMetaData().getURL());
} else {
log.error("连接数据源失败!");
}
}
}

View File

@ -0,0 +1,63 @@
package io.github.dunwu.javadb;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Objects;
/**
* user
*
* @author <a href="mailto:forbreak@163.com">Zhang Peng</a>
* @since 2019-11-18
*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String address;
private String email;
public User(String name, Integer age, String address, String email) {
this.name = name;
this.age = age;
this.address = address;
this.email = email;
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
User user = (User) o;
if (id != null && id.equals(user.id)) {
return true;
}
return name.equals(user.name);
}
}

View File

@ -0,0 +1,41 @@
package io.github.dunwu.javadb;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* user Dao
*
* @author <a href="mailto:forbreak@163.com">Zhang Peng</a>
* @since 2019-11-18
*/
public interface UserDao {
// DML
// -------------------------------------------------------------------
void insert(User user);
void batchInsert(List<User> users);
void deleteByName(String name);
void deleteAll();
void update(User user);
Integer count();
List<User> list();
User queryByName(String name);
JdbcTemplate getJdbcTemplate();
// DDL
// -------------------------------------------------------------------
void truncate();
void recreateTable();
}

View File

@ -0,0 +1,36 @@
package io.github.dunwu.javadb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
import javax.annotation.PostConstruct;
/**
* @author <a href="mailto:forbreak@163.com">Zhang Peng</a>
* @since 2020-10-11
*/
@Slf4j
@Component
public class UserDaoExecutor {
private final UserDao userDao;
public UserDaoExecutor(UserDao userDao) {
this.userDao = userDao;
}
@PostConstruct
public void method() {
if (userDao != null) {
log.info("Connect to datasource success.");
} else {
log.error("Connect to datasource failed!");
return;
}
List<User> list = userDao.list();
list.forEach(item -> log.info(item.toString()));
}
}

View File

@ -0,0 +1,114 @@
package io.github.dunwu.javadb;
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
*
* @author <a href="mailto:forbreak@163.com">Zhang Peng</a>
* @since 2019-11-18
*/
@Repository
public class UserDaoImpl implements UserDao {
private final JdbcTemplate jdbcTemplate;
public UserDaoImpl(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<User> users) {
String sql = "INSERT INTO user(name, age, address, email) VALUES(?, ?, ?, ?)";
List<Object[]> 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<User> 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 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);
}
}

View File

@ -0,0 +1,8 @@
spring.datasource.url = jdbc:mysql://localhost:3306/db_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

View File

@ -0,0 +1,12 @@
${AnsiColor.BRIGHT_YELLOW}${AnsiStyle.BOLD}
________ ___ ___ ________ ___ __ ___ ___
|\ ___ \|\ \|\ \|\ ___ \|\ \ |\ \|\ \|\ \
\ \ \_|\ \ \ \\\ \ \ \\ \ \ \ \ \ \ \ \ \\\ \
\ \ \ \\ \ \ \\\ \ \ \\ \ \ \ \ __\ \ \ \ \\\ \
\ \ \_\\ \ \ \\\ \ \ \\ \ \ \ \|\__\_\ \ \ \\\ \
\ \_______\ \_______\ \__\\ \__\ \____________\ \_______\
\|_______|\|_______|\|__| \|__|\|____________|\|_______|
${AnsiColor.CYAN}${AnsiStyle.BOLD}
:: Java :: (v${java.version})
:: Spring Boot :: (v${spring-boot.version})
${AnsiStyle.NORMAL}

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%boldYellow(%thread)] [%highlight(%-5level)] %boldGreen(%c{36}.%M) - %boldBlue(%m%n)
</pattern>
</encoder>
</appender>
<logger name="io.github.dunwu.javadb" level="INFO" />
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration>

View File

@ -0,0 +1,10 @@
-- -------------------------------------------------------------------
-- 运行本项目的初始化 DML 脚本
-- Mysql 知识点可以参考:
-- https://dunwu.github.io/db-tutorial/#/sql/mysql/README
-- -------------------------------------------------------------------
INSERT INTO `user` (`name`, `age`, `address`, `email`)
VALUES ('张三', 18, '北京', 'xxx@163.com');
INSERT INTO `user` (`name`, `age`, `address`, `email`)
VALUES ('李四', 19, '上海', 'xxx@163.com');

View File

@ -0,0 +1,18 @@
-- -------------------------------------------------------------------
-- 运行本项目的初始化 DDL 脚本
-- Mysql 知识点可以参考:
-- https://dunwu.github.io/db-tutorial/#/sql/mysql/README
-- -------------------------------------------------------------------
-- 创建用户表
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`)
);

View File

@ -20,7 +20,7 @@ public class MysqlDemoTest {
private static final String DB_PORT = "3306";
private static final String DB_SCHEMA = "sakila";
private static final String DB_SCHEMA = "db_tutorial";
private static final String DB_USER = "root";
@ -37,9 +37,6 @@ public class MysqlDemoTest {
try {
final String DB_URL = String.format("jdbc:mysql://%s:%s/%s", DB_HOST, DB_PORT, DB_SCHEMA);
connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
// connection =
// DriverManager.getConnection("jdbc:mysql://localhost:3306/sakila?" +
// "user=root&password=root");
statement = connection.createStatement();
} catch (SQLException e) {
e.printStackTrace();
@ -58,20 +55,20 @@ public class MysqlDemoTest {
}
@Test
public void testString() {
final String sql = "select * from actor limit 10";
public void testQuery() {
final String sql = "SELECT * FROM `user` LIMIT 10";
try {
ResultSet rs = statement.executeQuery(sql);
// 展开结果集数据库
while (rs.next()) {
// 通过字段检索
int id = rs.getInt("actor_id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
Date lastUpdate = rs.getDate("last_update");
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
String email = rs.getString("email");
// 输出数据
logger.debug("actor_id: {}, first_name: {}, last_name: {}, last_update: {}", id, firstName, lastName,
lastUpdate.toLocalDate());
logger.info("id: {}, name: {}, age: {}, address: {}, email: {}", id, name, age, address, email);
}
} catch (SQLException e) {
e.printStackTrace();

View File

@ -0,0 +1,87 @@
package io.github.dunwu.javadb;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
@Rollback
@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SpringBootDataJdbcApplication.class })
public class SpringBootDataJdbcTest {
private static final Logger log = LoggerFactory.getLogger(SpringBootDataJdbcTest.class);
@Autowired
private UserDao userDAO;
@Before
public void before() {
userDAO.truncate();
}
@Test
public void insert() {
userDAO.insert(new User("张三", 18, "北京", "user1@163.com"));
User linda = userDAO.queryByName("张三");
assertThat(linda).isNotNull();
}
@Test
public void batchInsert() {
List<User> 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();
assertThat(count).isEqualTo(4);
List<User> list = userDAO.list();
assertThat(list).isNotEmpty().hasSize(4);
list.forEach(user -> {
log.info(user.toString());
});
}
@Test
public void delete() {
List<User> 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("张三");
assertThat(user).isNull();
userDAO.deleteAll();
List<User> list = userDAO.list();
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("张三丰");
assertThat(newUser).isNotNull();
}
}

View File

@ -1,45 +0,0 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!-- logback中一共有5种有效级别分别是TRACE、DEBUG、INFO、WARN、ERROR优先级依次从低到高 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<property name="FILE_NAME" value="javadb" />
<!-- 将记录日志打印到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] [%-5p] %c{36}.%M - %m%n</pattern>
</encoder>
</appender>
<!-- RollingFileAppender begin -->
<appender name="ALL" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 根据时间来制定滚动策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${user.dir}/logs/${FILE_NAME}-all.%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<!-- 根据文件大小来制定滚动策略 -->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>30MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] [%-5p] %c{36}.%M - %m%n</pattern>
</encoder>
</appender>
<!-- RollingFileAppender end -->
<!-- logger begin -->
<!-- 本项目的日志记录,分级打印 -->
<logger name="io.github.dunwu" level="TRACE">
<appender-ref ref="ALL" />
</logger>
<root level="TRACE">
<appender-ref ref="STDOUT" />
</root>
<!-- logger end -->
</configuration>

View File

@ -14,11 +14,11 @@
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<spring.version>4.3.13.RELEASE</spring.version>
<spring.version>5.2.8.RELEASE</spring.version>
<logback.version>1.2.3</logback.version>
<jedis.version>2.9.0</jedis.version>
<redisson.version>3.7.2</redisson.version>
<junit.version>4.12</junit.version>
<junit.version>4.13.1</junit.version>
</properties>
<dependencies>

View File

@ -18,9 +18,9 @@ import java.util.Set;
/**
* @author Zhang Peng
*/
@ActiveProfiles("test")
@ActiveProfiles("dev")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/applicationContext.xml"})
@ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
public class JedisPoolDemoTest {
private static Logger logger = LoggerFactory.getLogger(JedisPoolDemoTest.class);

View File

@ -33,11 +33,11 @@
<!-- logger begin -->
<!-- 本项目的日志记录,分级打印 -->
<logger name="io.github.dunwu" level="TRACE">
<logger name="io.github.dunwu" level="DEBUG">
<appender-ref ref="ALL" />
</logger>
<root level="TRACE">
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<!-- logger end -->

View File

@ -26,7 +26,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<version>2.0.206</version>
</dependency>
<!-- db end -->
</dependencies>
@ -45,7 +45,7 @@
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<version>2.0.206</version>
</dependency>
</dependencies>
</plugin>

View File

@ -16,7 +16,7 @@
<logback.version>1.2.3</logback.version>
<jedis.version>2.9.0</jedis.version>
<junit.version>4.12</junit.version>
<junit.version>4.13.1</junit.version>
</properties>
<dependencies>