在Spring Boot中使用JdbcTemplate操作数据库
基于GitHub项目xkcoding/**spring-boot-demo**进行学习
项目地址:https://github.com/xkcoding/spring-boot-demo
spring-boot-starter-jdbc
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<artifactId>spring-boot-demo-orm-jdbctemplateartifactId>
<version>1.0.0-SNAPSHOTversion>
<packaging>jarpackaging>
<name>spring-boot-demo-orm-jdbctemplatename>
<description>Demo project for Spring Bootdescription>
<parent>
<groupId>com.xkcodinggroupId>
<artifactId>spring-boot-demoartifactId>
<version>1.0.0-SNAPSHOTversion>
parent>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-jdbcartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
dependencies>
<build>
<finalName>spring-boot-demo-orm-jdbctemplatefinalName>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
plugin>
plugins>
build>
project>
server:
port: 8080
servlet:
context-path: /demo
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
username: root
password: jkl555444
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
initialization-mode: always
continue-on-error: true
# 建表sql
schema:
- "classpath:db/schema.sql"
# 数据sql
data:
- "classpath:db/data.sql"
hikari:
minimum-idle: 5
connection-test-query: SELECT 1 FROM DUAL
maximum-pool-size: 20
auto-commit: true
idle-timeout: 30000
pool-name: SpringBootDemoHikariCP
max-lifetime: 60000
connection-timeout: 30000
# 日志记录
logging:
level:
com.xkcoding: debug
DROP TABLE IF EXISTS `orm_user`;
CREATE TABLE `orm_user` (
`id` INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键',
`name` VARCHAR(32) NOT NULL UNIQUE COMMENT '用户名',
`password` VARCHAR(32) NOT NULL COMMENT '加密后的密码',
`salt` VARCHAR(32) NOT NULL COMMENT '加密使用的盐',
`email` VARCHAR(32) NOT NULL UNIQUE COMMENT '邮箱',
`phone_number` VARCHAR(15) NOT NULL UNIQUE COMMENT '手机号码',
`status` INT(2) NOT NULL DEFAULT 1 COMMENT '状态,-1:逻辑删除,0:禁用,1:启用',
`create_time` DATETIME NOT NULL DEFAULT NOW() COMMENT '创建时间',
`last_login_time` DATETIME DEFAULT NULL COMMENT '上次登录时间',
`last_update_time` DATETIME NOT NULL DEFAULT NOW() COMMENT '上次更新时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Spring Boot Demo Orm 系列示例表';
INSERT INTO `orm_user`(`id`,`name`,`password`,`salt`,`email`,`phone_number`) VALUES (1, 'user_1', 'ff342e862e7c3285cdc07e56d6b8973b', '412365a109674b2dbb1981ed561a4c70', '[email protected]', '17300000001');
INSERT INTO `orm_user`(`id`,`name`,`password`,`salt`,`email`,`phone_number`) VALUES (2, 'user_2', '6c6bf02c8d5d3d128f34b1700cb1e32c', 'fcbdd0e8a9404a5585ea4e01d0e4d7a0', '[email protected]', '17300000002');
package com.xkcoding.orm.jdbctemplate.constant;
/**
*
* 常量池
*
*
* @package: com.xkcoding.orm.jdbctemplate.constant
* @description: 常量池
* @author: yangkai.shen
* @date: Created in 2018/10/15 10:59 AM
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
public interface Const {
/**
* 加密盐前缀
*/
String SALT_PREFIX = "::SpringBootDemo::";
/**
* 逗号分隔符
*/
String SEPARATOR_COMMA = ",";
}
package com.xkcoding.orm.jdbctemplate.entity;
import com.xkcoding.orm.jdbctemplate.annotation.Pk;
import com.xkcoding.orm.jdbctemplate.annotation.Column;
import com.xkcoding.orm.jdbctemplate.annotation.Table;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
*
* 用户实体类
*
*
* @package: com.xkcoding.orm.jdbctemplate.entity
* @description: 用户实体类
* @author: yangkai.shen
* @date: Created in 2018/10/15 10:45 AM
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
@Data
@Table(name = "orm_user")
public class User implements Serializable {
/**
* 主键
*/
@Pk
private Long id;
/**
* 用户名
*/
private String name;
/**
* 加密后的密码
*/
private String password;
/**
* 加密使用的盐
*/
private String salt;
/**
* 邮箱
*/
private String email;
/**
* 手机号码
*/
@Column(name = "phone_number")
private String phoneNumber;
/**
* 状态,-1:逻辑删除,0:禁用,1:启用
*/
private Integer status;
/**
* 创建时间
*/
@Column(name = "create_time")
private Date createTime;
/**
* 上次登录时间
*/
@Column(name = "last_login_time")
private Date lastLoginTime;
/**
* 上次更新时间
*/
@Column(name = "last_update_time")
private Date lastUpdateTime;
}
package com.xkcoding.orm.jdbctemplate.dao.base;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xkcoding.orm.jdbctemplate.annotation.Column;
import com.xkcoding.orm.jdbctemplate.annotation.Ignore;
import com.xkcoding.orm.jdbctemplate.annotation.Pk;
import com.xkcoding.orm.jdbctemplate.annotation.Table;
import com.xkcoding.orm.jdbctemplate.constant.Const;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
*
* Dao基类
*
*
* @package: com.xkcoding.orm.jdbctemplate.dao.base
* @description: Dao基类
* @author: yangkai.shen
* @date: Created in 2018/10/15 11:28 AM
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
@Slf4j
public class BaseDao<T, P> {
private JdbcTemplate jdbcTemplate; // jdbc模板
private Class<T> clazz; // 作用的类
@SuppressWarnings(value = "unchecked")
public BaseDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
/**
* 通用插入,自增列需要添加 {@link Pk} 注解
*
* @param t 对象
* @param ignoreNull 是否忽略 null 值
* @return 操作的行数
*/
protected Integer insert(T t, Boolean ignoreNull) {
// 获取表名
String table = getTableName(t);
// 获取字段列表
List<Field> filterField = getField(t, ignoreNull);
// 获取列
List<String> columnList = getColumns(filterField);
// 使用逗号分隔,将columnList中的多个对象转换为一个字符串
String columns = StrUtil.join(Const.SEPARATOR_COMMA, columnList);
// 构造占位符,占位符的数量和columnList中字段数量一致
String params = StrUtil.repeatAndJoin("?", columnList.size(), Const.SEPARATOR_COMMA);
// 构造值,放入values数组中
Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();
// 构造sql语句
String sql = StrUtil.format("INSERT INTO {table} ({columns}) VALUES ({params})", Dict.create().set("table", table).set("columns", columns).set("params", params));
log.debug("【执行SQL】SQL:{}", sql);
log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
// 执行update,参数为带占位符的sql和对应的数值
return jdbcTemplate.update(sql, values);
}
/**
* 通用根据主键删除
*
* @param pk 主键
* @return 影响行数
*/
protected Integer deleteById(P pk) {
String tableName = getTableName();
String sql = StrUtil.format("DELETE FROM {table} where id = ?", Dict.create().set("table", tableName));
log.debug("【执行SQL】SQL:{}", sql);
log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(pk));
return jdbcTemplate.update(sql, pk);
}
/**
* 通用根据主键更新,自增列需要添加 {@link Pk} 注解
*
* @param t 对象
* @param pk 主键
* @param ignoreNull 是否忽略 null 值
* @return 操作的行数
*/
protected Integer updateById(T t, P pk, Boolean ignoreNull) {
String tableName = getTableName(t);
List<Field> filterField = getField(t, ignoreNull);
List<String> columnList = getColumns(filterField);
List<String> columns = columnList.stream().map(s -> StrUtil.appendIfMissing(s, " = ?")).collect(Collectors.toList());
String params = StrUtil.join(Const.SEPARATOR_COMMA, columns);
// 构造值
List<Object> valueList = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).collect(Collectors.toList());
valueList.add(pk);
Object[] values = ArrayUtil.toArray(valueList, Object.class);
String sql = StrUtil.format("UPDATE {table} SET {params} where id = ?", Dict.create().set("table", tableName).set("params", params));
log.debug("【执行SQL】SQL:{}", sql);
log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
return jdbcTemplate.update(sql, values);
}
/**
* 通用根据主键查询单条记录
*
* @param pk 主键
* @return 单条记录
*/
public T findOneById(P pk) {
String tableName = getTableName();
String sql = StrUtil.format("SELECT * FROM {table} where id = ?", Dict.create().set("table", tableName));
RowMapper<T> rowMapper = new BeanPropertyRowMapper<>(clazz);
log.debug("【执行SQL】SQL:{}", sql);
log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(pk));
return jdbcTemplate.queryForObject(sql, new Object[]{pk}, rowMapper);
}
/**
* 根据对象查询
*
* @param t 查询条件
* @return 对象列表
*/
public List<T> findByExample(T t) {
String tableName = getTableName(t);
List<Field> filterField = getField(t, true);
List<String> columnList = getColumns(filterField);
List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());
String where = StrUtil.join(" ", columns);
// 构造值
Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();
String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
log.debug("【执行SQL】SQL:{}", sql);
log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
List<T> ret = CollUtil.newArrayList();
maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
return ret;
}
/**
* 获取表名
*
* @param t 对象
* @return 表名
*/
private String getTableName(T t) {
Table tableAnnotation = t.getClass().getAnnotation(Table.class);
if (ObjectUtil.isNotNull(tableAnnotation)) {
return StrUtil.format("`{}`", tableAnnotation.name());
} else {
return StrUtil.format("`{}`", t.getClass().getName().toLowerCase());
}
}
/**
* 获取表名
*
* @return 表名
*/
private String getTableName() {
Table tableAnnotation = clazz.getAnnotation(Table.class);
if (ObjectUtil.isNotNull(tableAnnotation)) {
return StrUtil.format("`{}`", tableAnnotation.name());
} else {
return StrUtil.format("`{}`", clazz.getName().toLowerCase());
}
}
/**
* 获取列
*
* @param fieldList 字段列表
* @return 列信息列表
*/
private List<String> getColumns(List<Field> fieldList) {
// 构造列
List<String> columnList = CollUtil.newArrayList();
for (Field field : fieldList) {
Column columnAnnotation = field.getAnnotation(Column.class);
String columnName;
if (ObjectUtil.isNotNull(columnAnnotation)) {
columnName = columnAnnotation.name();
} else {
columnName = field.getName();
}
columnList.add(StrUtil.format("`{}`", columnName));
}
return columnList;
}
/**
* 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列}
*
* @param t 对象
* @param ignoreNull 是否忽略空值
* @return 字段列表
*/
private List<Field> getField(T t, Boolean ignoreNull) {
// 获取所有字段,包含父类中的字段
Field[] fields = ReflectUtil.getFields(t.getClass());
// 过滤数据库中不存在的字段,以及自增列
List<Field> filterField;
Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class)));
// 是否过滤字段值为null的字段
if (ignoreNull) {
filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList());
} else {
filterField = fieldStream.collect(Collectors.toList());
}
return filterField;
}
}
package com.xkcoding.orm.jdbctemplate.dao;
import com.xkcoding.orm.jdbctemplate.dao.base.BaseDao;
import com.xkcoding.orm.jdbctemplate.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
*
* User Dao
*
*
* @package: com.xkcoding.orm.jdbctemplate.dao
* @description: User Dao
* @author: yangkai.shen
* @date: Created in 2018/10/15 11:15 AM
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
@Repository
public class UserDao extends BaseDao<User, Long> {
@Autowired
public UserDao(JdbcTemplate jdbcTemplate) {
super(jdbcTemplate);
}
/**
* 保存用户
*
* @param user 用户对象
* @return 操作影响行数
*/
public Integer insert(User user) {
return super.insert(user, true);
}
/**
* 根据主键删除用户
*
* @param id 主键id
* @return 操作影响行数
*/
public Integer delete(Long id) {
return super.deleteById(id);
}
/**
* 更新用户
*
* @param user 用户对象
* @param id 主键id
* @return 操作影响行数
*/
public Integer update(User user, Long id) {
return super.updateById(user, id, true);
}
/**
* 根据主键获取用户
*
* @param id 主键id
* @return id对应的用户
*/
public User selectById(Long id) {
return super.findOneById(id);
}
/**
* 根据查询条件获取用户列表
*
* @param user 用户查询条件
* @return 用户列表
*/
public List<User> selectUserList(User user) {
return super.findByExample(user);
}
}
package com.xkcoding.orm.jdbctemplate.service;
import com.xkcoding.orm.jdbctemplate.entity.User;
import java.util.List;
/**
*
* User Service
*
*
* @package: com.xkcoding.orm.jdbctemplate.service
* @description: User Service
* @author: yangkai.shen
* @date: Created in 2018/10/15 1:51 PM
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
public interface IUserService {
/**
* 保存用户
*
* @param user 用户实体
* @return 保存成功 {@code true} 保存失败 {@code false}
*/
Boolean save(User user);
/**
* 删除用户
*
* @param id 主键id
* @return 删除成功 {@code true} 删除失败 {@code false}
*/
Boolean delete(Long id);
/**
* 更新用户
*
* @param user 用户实体
* @param id 主键id
* @return 更新成功 {@code true} 更新失败 {@code false}
*/
Boolean update(User user, Long id);
/**
* 获取单个用户
*
* @param id 主键id
* @return 单个用户对象
*/
User getUser(Long id);
/**
* 获取用户列表
*
* @param user 用户实体
* @return 用户列表
*/
List<User> getUser(User user);
}
package com.xkcoding.orm.jdbctemplate.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.xkcoding.orm.jdbctemplate.constant.Const;
import com.xkcoding.orm.jdbctemplate.dao.UserDao;
import com.xkcoding.orm.jdbctemplate.entity.User;
import com.xkcoding.orm.jdbctemplate.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*
* User Service Implement
*
*
* @package: com.xkcoding.orm.jdbctemplate.service.impl
* @description: User Service Implement
* @author: yangkai.shen
* @date: Created in 2018/10/15 1:53 PM
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
@Service
public class UserServiceImpl implements IUserService {
private final UserDao userDao;
@Autowired
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
/**
* 保存用户
*
* @param user 用户实体
* @return 保存成功 {@code true} 保存失败 {@code false}
*/
@Override
public Boolean save(User user) {
// 将需要加密的密码进行盐加密
String rawPass = user.getPassword();
String salt = IdUtil.simpleUUID();
String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt);
user.setPassword(pass);
user.setSalt(salt);
return userDao.insert(user) > 0;
}
/**
* 删除用户
*
* @param id 主键id
* @return 删除成功 {@code true} 删除失败 {@code false}
*/
@Override
public Boolean delete(Long id) {
return userDao.delete(id) > 0;
}
/**
* 更新用户
*
* @param user 用户实体
* @param id 主键id
* @return 更新成功 {@code true} 更新失败 {@code false}
*/
@Override
public Boolean update(User user, Long id) {
User exist = getUser(id);
if (StrUtil.isNotBlank(user.getPassword())) {
String rawPass = user.getPassword();
String salt = IdUtil.simpleUUID();
String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt);
user.setPassword(pass);
user.setSalt(salt);
}
BeanUtil.copyProperties(user, exist, CopyOptions.create().setIgnoreNullValue(true));
exist.setLastUpdateTime(new DateTime());
return userDao.update(exist, id) > 0;
}
/**
* 获取单个用户
*
* @param id 主键id
* @return 单个用户对象
*/
@Override
public User getUser(Long id) {
return userDao.findOneById(id);
}
/**
* 获取用户列表
*
* @param user 用户实体
* @return 用户列表
*/
@Override
public List<User> getUser(User user) {
return userDao.findByExample(user);
}
}
package com.xkcoding.orm.jdbctemplate.controller;
import cn.hutool.core.lang.Dict;
import com.xkcoding.orm.jdbctemplate.entity.User;
import com.xkcoding.orm.jdbctemplate.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
*
* User Controller
*
*
* @package: com.xkcoding.orm.jdbctemplate.controller
* @description: User Controller
* @author: yangkai.shen
* @date: Created in 2018/10/15 1:58 PM
* @copyright: Copyright (c) 2018
* @version: V1.0
* @modified: yangkai.shen
*/
@RestController
@Slf4j
public class UserController {
private final IUserService userService;
@Autowired
public UserController(IUserService userService) {
this.userService = userService;
}
@PostMapping("/user")
// 从RequestBody获取user的相关字段信息
public Dict save(@RequestBody User user) {
// 调用service层进行保存
Boolean save = userService.save(user);
// set方法return this,可以使用链式编程
// 将状态码code、消息msg、数据data存储到字典中
return Dict.create().set("code", save ? 200 : 500).set("msg", save ? "成功" : "失败").set("data", save ? user : null);
}
@DeleteMapping("/user/{id}")
public Dict delete(@PathVariable Long id) {
Boolean delete = userService.delete(id);
return Dict.create().set("code", delete ? 200 : 500).set("msg", delete ? "成功" : "失败");
}
@PutMapping("/user/{id}")
public Dict update(@RequestBody User user, @PathVariable Long id) {
Boolean update = userService.update(user, id);
return Dict.create().set("code", update ? 200 : 500).set("msg", update ? "成功" : "失败").set("data", update ? user : null);
}
@GetMapping("/user/{id}")
public Dict getUser(@PathVariable Long id) {
User user = userService.getUser(id);
return Dict.create().set("code", 200).set("msg", "成功").set("data", user);
}
@GetMapping("/user")
public Dict getUser(User user) {
List<User> userList = userService.getUser(user);
return Dict.create().set("code", 200).set("msg", "成功").set("data", userList);
}
}
@PostMapping("/user")
// 从RequestBody获取user的相关字段信息
public Dict save(@RequestBody User user) {
// 调用service层进行保存
Boolean save = userService.save(user);
// set方法return this,可以使用链式编程
// 将状态码code、消息msg、数据data存储到字典中
return Dict.create().set("code", save ? 200 : 500).set("msg", save ? "成功" : "失败").set("data", save ? user : null);
}
/**
* 保存用户
*
* @param user 用户实体
* @return 保存成功 {@code true} 保存失败 {@code false}
*/
@Override
public Boolean save(User user) {
// 将需要加密的密码进行盐加密
String rawPass = user.getPassword();
String salt = IdUtil.simpleUUID();
String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt);
user.setPassword(pass);
user.setSalt(salt);
return userDao.insert(user) > 0;
}
/**
* 保存用户
*
* @param user 用户对象
* @return 操作影响行数
*/
public Integer insert(User user) {
return super.insert(user, true);
}
/**
* 通用插入,自增列需要添加 {@link Pk} 注解
*
* @param t 对象
* @param ignoreNull 是否忽略 null 值
* @return 操作的行数
*/
protected Integer insert(T t, Boolean ignoreNull) {
// 获取表名
String table = getTableName(t);
// 获取字段列表
List<Field> filterField = getField(t, ignoreNull);
// 获取列
List<String> columnList = getColumns(filterField);
// 使用逗号分隔,将columnList中的多个对象转换为一个字符串
String columns = StrUtil.join(Const.SEPARATOR_COMMA, columnList);
// 构造占位符,占位符的数量和columnList中字段数量一致
String params = StrUtil.repeatAndJoin("?", columnList.size(), Const.SEPARATOR_COMMA);
// 构造值,放入values数组中
Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();
// 构造sql语句
String sql = StrUtil.format("INSERT INTO {table} ({columns}) VALUES ({params})", Dict.create().set("table", table).set("columns", columns).set("params", params));
log.debug("【执行SQL】SQL:{}", sql);
log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
// 执行update,参数为带占位符的sql和对应的数值
return jdbcTemplate.update(sql, values);
}