mirror of
https://gitee.com/yudaocode/SpringBoot-Labs.git
synced 2026-09-03 05:53:54 +08:00
增加 JdbcTemplate 示例
This commit is contained in:
35
lab-14/lab-14-jdbctemplate/pom.xml
Normal file
35
lab-14/lab-14-jdbctemplate/pom.xml
Normal file
@@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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">
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.1.3.RELEASE</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>lab-14-jdbctemplate</artifactId>
|
||||
|
||||
<dependencies>
|
||||
<!-- 实现对数据库连接池的自动化配置 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency> <!-- 本示例,我们使用 MySQL -->
|
||||
<groupId>mysql</groupId>
|
||||
<artifactId>mysql-connector-java</artifactId>
|
||||
<version>5.1.48</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 方便等会写单元测试 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,7 @@
|
||||
package cn.iocoder.springboot.lab14.jdbctemplate;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package cn.iocoder.springboot.lab14.jdbctemplate.dao;
|
||||
|
||||
import cn.iocoder.springboot.lab14.jdbctemplate.dataobject.UserDO;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.BeanPropertyRowMapper;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.PreparedStatementCreatorFactory;
|
||||
import org.springframework.jdbc.core.SqlParameter;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
import org.springframework.jdbc.support.KeyHolder;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.sql.Types;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Repository
|
||||
public class UserDao {
|
||||
|
||||
/**
|
||||
* 声明 INSERT 操作的 PreparedStatementCreatorFactory 对象
|
||||
*/
|
||||
private static final PreparedStatementCreatorFactory INSERT_PREPARED_STATEMENT_CREATOR_FACTORY
|
||||
= new PreparedStatementCreatorFactory("INSERT INTO users(username, password, create_time) VALUES(?, ?, ?)");
|
||||
|
||||
static {
|
||||
// 设置返回主键
|
||||
INSERT_PREPARED_STATEMENT_CREATOR_FACTORY.setReturnGeneratedKeys(true);
|
||||
INSERT_PREPARED_STATEMENT_CREATOR_FACTORY.setGeneratedKeysColumnNames("id");
|
||||
// 设置每个占位符的类型
|
||||
INSERT_PREPARED_STATEMENT_CREATOR_FACTORY.addParameter(new SqlParameter(Types.VARCHAR));
|
||||
INSERT_PREPARED_STATEMENT_CREATOR_FACTORY.addParameter(new SqlParameter(Types.VARCHAR));
|
||||
INSERT_PREPARED_STATEMENT_CREATOR_FACTORY.addParameter(new SqlParameter(Types.TIMESTAMP));
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate template;
|
||||
|
||||
/**
|
||||
* 使用 PreparedStatementCreator 实现插入数据
|
||||
*
|
||||
* @param entity 实体
|
||||
* @return 影响行数
|
||||
*/
|
||||
public int insert(UserDO entity) {
|
||||
// 创建 KeyHolder 对象,设置返回的主键 ID
|
||||
KeyHolder keyHolder = new GeneratedKeyHolder();
|
||||
// 执行插入操作
|
||||
int updateCounts = template.update(INSERT_PREPARED_STATEMENT_CREATOR_FACTORY.newPreparedStatementCreator(
|
||||
Arrays.asList(entity.getUsername(), entity.getPassword(), entity.getCreateTime())
|
||||
), keyHolder);
|
||||
// 设置 ID 主键到 entity 实体中
|
||||
if (keyHolder.getKey() != null) {
|
||||
entity.setId(keyHolder.getKey().intValue());
|
||||
}
|
||||
// 返回影响行数
|
||||
return updateCounts;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用 SimpleJdbcInsert 实现插入数据
|
||||
*
|
||||
* @param entity 实体
|
||||
* @return 影响行数
|
||||
*/
|
||||
public int insert0(UserDO entity) {
|
||||
// 创建 SimpleJdbcInsert 对象
|
||||
SimpleJdbcInsert insertOp = new SimpleJdbcInsert(template);
|
||||
insertOp.setTableName("users");
|
||||
insertOp.setColumnNames(Arrays.asList("username", "password", "create_time"));
|
||||
insertOp.setGeneratedKeyName("id");
|
||||
// 拼接参数
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("username", entity.getUsername());
|
||||
params.put("password", entity.getPassword());
|
||||
params.put("create_time", entity.getCreateTime());
|
||||
// 执行插入操作
|
||||
Number id = insertOp.executeAndReturnKey(params);
|
||||
// 设置 ID 主键到 entity 实体中
|
||||
entity.setId(id.intValue());
|
||||
// 返回影响行数
|
||||
return 1;
|
||||
}
|
||||
|
||||
public int updateById(UserDO entity) {
|
||||
// JdbcTemplate 生成更新的动态 SQL 不是很方便,需要自己二次封装。类似 SimpleJdbcInsert 对象
|
||||
return template.update("UPDATE users SET password = ? WHERE id = ?", entity.getPassword(),
|
||||
entity.getId());
|
||||
}
|
||||
|
||||
public int deleteById(Integer id) {
|
||||
return template.update("DELETE FROM users WHERE id = ?", id);
|
||||
}
|
||||
|
||||
public UserDO selectById(Integer id) {
|
||||
return template.queryForObject("SELECT id, username, password, create_time FROM users WHERE id = ?",
|
||||
new BeanPropertyRowMapper<>(UserDO.class), // 结果转换成对应的对象
|
||||
id);
|
||||
}
|
||||
|
||||
public UserDO selectByUsername(String username) {
|
||||
return template.queryForObject("SELECT id, username, password, create_time FROM users WHERE username = ? LIMIT 1",
|
||||
new BeanPropertyRowMapper<>(UserDO.class), // 结果转换成对应的对象
|
||||
username);
|
||||
}
|
||||
|
||||
public List<UserDO> selectByIds(List<Integer> ids) {
|
||||
// 创建 NamedParameterJdbcTemplate 对象
|
||||
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(template);
|
||||
// 拼接参数
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("ids", ids);
|
||||
// 执行查询
|
||||
return namedParameterJdbcTemplate.query(
|
||||
"SELECT id, username, password, create_time FROM users WHERE id IN (:ids)", // 使用 :ids 作为占位服务
|
||||
params,
|
||||
new BeanPropertyRowMapper<>(UserDO.class) // 结果转换成对应的对象
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package cn.iocoder.springboot.lab14.jdbctemplate.dataobject;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 用户 DO
|
||||
*/
|
||||
public class UserDO {
|
||||
|
||||
/**
|
||||
* 用户编号
|
||||
*/
|
||||
private Integer id;
|
||||
/**
|
||||
* 账号
|
||||
*/
|
||||
private String username;
|
||||
/**
|
||||
* 密码(明文)
|
||||
*
|
||||
* ps:生产环境下,千万不要明文噢
|
||||
*/
|
||||
private String password;
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private Date createTime;
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public UserDO setId(Integer id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public UserDO setUsername(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public UserDO setPassword(String password) {
|
||||
this.password = password;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Date getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public UserDO setCreateTime(Date createTime) {
|
||||
this.createTime = createTime;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "UserDO{" +
|
||||
"id=" + id +
|
||||
", username='" + username + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
", createTime=" + createTime +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
spring:
|
||||
# datasource 数据源配置内容
|
||||
datasource:
|
||||
url: jdbc:mysql://47.112.193.81:3306/testb5f4?useSSL=false&useUnicode=true&characterEncoding=UTF-8
|
||||
driver-class-name: com.mysql.jdbc.Driver
|
||||
username: testb5f4
|
||||
password: F4df4db0ed86@11
|
||||
@@ -0,0 +1,69 @@
|
||||
package cn.iocoder.springboot.lab14.jdbctemplate.dao;
|
||||
|
||||
import cn.iocoder.springboot.lab14.jdbctemplate.Application;
|
||||
import cn.iocoder.springboot.lab14.jdbctemplate.dataobject.UserDO;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = Application.class)
|
||||
public class UserDaoTest {
|
||||
|
||||
@Autowired
|
||||
private UserDao userDao;
|
||||
|
||||
@Test
|
||||
public void testInsert() {
|
||||
UserDO user = new UserDO().setUsername(UUID.randomUUID().toString())
|
||||
.setPassword("nicai").setCreateTime(new Date());
|
||||
userDao.insert(user);
|
||||
System.out.println(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInsert0() {
|
||||
UserDO user = new UserDO().setUsername(UUID.randomUUID().toString())
|
||||
.setPassword("nicai").setCreateTime(new Date());
|
||||
userDao.insert0(user);
|
||||
System.out.println(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateById() {
|
||||
UserDO updateUser = new UserDO().setId(1)
|
||||
.setPassword("wobucai");
|
||||
userDao.updateById(updateUser);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteById() {
|
||||
userDao.deleteById(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectById() {
|
||||
UserDO user = userDao.selectById(1);
|
||||
System.out.println(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectByUsername() {
|
||||
UserDO user = userDao.selectByUsername("yunai");
|
||||
System.out.println(user);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectByIds() {
|
||||
List<UserDO> users = userDao.selectByIds(Arrays.asList(1, 5));
|
||||
System.out.println("users:" + users.size());
|
||||
}
|
||||
|
||||
}
|
||||
19
lab-14/pom.xml
Normal file
19
lab-14/pom.xml
Normal file
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<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">
|
||||
<parent>
|
||||
<artifactId>labs-parent</artifactId>
|
||||
<groupId>cn.iocoder.springboot.labs</groupId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>lab-14</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<modules>
|
||||
<module>lab-14-jdbctemplate</module>
|
||||
</modules>
|
||||
|
||||
|
||||
</project>
|
||||
Reference in New Issue
Block a user