① Spring Boot 框架为 SQL 数据库提供了广泛的支持,既有用 JdbcTemplate 直接访问 JDBC,同时支持“object relational mapping”技术(如 Hibernate、MyBatis)。Spring Data 独立的项目提供对多种关系型和非关系型数据库的访问支持。比如 MySQL、Oracle、MongDB、Redis、R2DBC、Apache Solr、Elasticsearch…
② Spring Boot 也支持嵌入式数据库比如 H2,HSQL,Derby。这些数据库只需要提供 jar 包就能在内存中维护数据。
③ 本篇博客主要讲解如何使用 Spring Boot 中的 JdbcTemplate 访问关系型数据库。
DataSourceProperties.java 是数据源的配置类,有那些可以配置的可以参看源码。
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
private ClassLoader classLoader;
private boolean generateUniqueName = true;
private String name;
private Class<? extends DataSource> type;
private String driverClassName;
private String url;
private String username;
private String password;
private String jndiName;
private EmbeddedDatabaseConnection embeddedDatabaseConnection;
private Xa xa = new Xa();
private String uniqueName;
}
DataSource 在Applicaton 配置文件中以 spring.datasource.* 作为配置项。
spring:
datasource:
url: jdbc:mysql://localhost:3306/自己的数据库名
username: root(自己的用户名,一般都是root)
password: 登录数据库的密码
Spring Boot 能够从 spring.datasource.url 推断所使用的数据驱动类,如果需要特殊指定请设置 spring.datasource.driverClassName 为驱动类的全限定名称。
Spring Boot 支持多种数据库连接池,优先使用 HikariCP,其次是 Tomcat pooling,再次是 Commons DBCP2,如果以上都没有,最后使用 Oracle UCP 连接池。当项目中 starter 依赖了 spring-boot-starter-jdbc 或者 spring-boot-stater-data-jpa 默认添加 HikariCP 连接池依赖,也就是默认使用 HikariCP 连接池。
# schema.sql 文件
DROP TABLE IF EXISTS `article`;
CREATE TABLE `article`
(
`id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
`user_id` int NOT NULL COMMENT '作者 ID',
`title` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '文章标题',
`summary` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '文章概要',
`read_count` int(11) UNSIGNED ZEROFILL NOT NULL COMMENT '阅读读数',
`create_time` datetime NOT NULL COMMENT '创建时间',
`update_time` datetime NOT NULL COMMENT '最后修改时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB
AUTO_INCREMENT = 1
CHARACTER SET = utf8mb4
COLLATE = UTF8MB4_0900_AI_CI
ROW_FORMAT = Dynamic;
DROP TABLE IF EXISTS `article_detail`;
CREATE TABLE `article_detail`
(
`id` int NOT NULL AUTO_INCREMENT COMMENT '注解',
`article_id` int NOT NULL COMMENT '文章 ID',
`content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '文章内容',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB
AUTO_INCREMENT = 1
CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci
ROW_FORMAT = Dynamic;
# data.sql 文件
-- ----------------------------
-- Records of article
-- ----------------------------
INSERT INTO `article`
VALUES (1, 2101, 'SpringBoot 核心注解', '核心注解的主要作用', 00000008976, '2023-01-16 12:11:12',
'2023-01-16 12:11:19');
INSERT INTO `article`
VALUES (2, 356752, 'JVM 调优', 'HotSpot 虚拟机详解', 00000000026, '2023-01-16 12:15:27', '2023-01-16 12:15:30');
-- ----------------------------
-- Records of article_detail
-- ----------------------------
INSERT INTO `article_detail`
VALUES (1, 1, '注解十分的重要,例如:SpringBootApplication');
public class ArticleDetail {
private Integer id;
private Integer userId;
private String summary;
private String title;
private Integer readCount;
private LocalDateTime createTime;
private LocalDateTime updateTime;
//全参构造、无参构造、toString、set和get方法
}
public class ArticleDetail {
private Integer id;
private Integer articleId;
private String content;
//全参构造、无参构造、toString、set和get方法
}
//Jdbc绑定Bean的源码
@ConfigurationProperties(prefix = "spring.jdbc")
public class JdbcProperties {
private final Template template = new Template();
public Template getTemplate() {
return this.template;
}
public static class Template {
/**
* Number of rows that should be fetched from the database when more rows are
* needed. Use -1 to use the JDBC driver's default configuration.
*/
private int fetchSize = -1;
/**
* Maximum number of rows. Use -1 to use the JDBC driver's default configuration.
*/
private int maxRows = -1;
/**
* Query timeout. Default is to use the JDBC driver's default configuration. If a
* duration suffix is not specified, seconds will be used.
*/
@DurationUnit(ChronoUnit.SECONDS)
private Duration queryTimeout;
}
}
@SpringBootTest
class JdbcTemplateApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void insert() {
String sql = "insert into article_detail (article_id, content) values (?, ?)";
int count = jdbcTemplate.update(sql, 2, "JVM 十分的重要,一定要去学习。");
System.out.println("插入的记录条数是:" + count);
}
@Test
void modify() {
String sql = "update article_detail set content = ? where id = ?";
int count = jdbcTemplate.update(sql, "Spring Boot 中的核心注解十分重要", 2);
System.out.println("修改的记录条数是:" + count);
}
@Test
void delete() {
String sql = "delete from article_detail where id = ?";
int count = jdbcTemplate.update(sql, 2);
System.out.println("删除的记录条数是:" + count);
}
}
@SpringBootTest
class JdbcTemplateApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void batchInsert() {
String sql = "insert into article_detail (article_id, content) values (?, ?)";
Object[] obj1 = {2, "JVM 十分的重要,一定要去学习。"};
Object[] obj2 = {1, "SpringBoot 十分的重要,一定要去学习。"};
Object[] obj3 = {2, "JVM 学习了之后一定会大有收获的"};
List<Object[]> list = new ArrayList<>();
list.add(obj1);
list.add(obj2);
list.add(obj3);
int[] count = jdbcTemplate.batchUpdate(sql, list);
System.out.println("插入的记录条数是:" + Arrays.toString(count));
}
@Test
void batchModify() {
String sql = "update article_detail set content = ? where id = ?";
Object[] obj1 = {"测试更新", 4};
Object[] obj2 = {"测试更新", 5};
Object[] obj3 = {"测试更新", 3};
List<Object[]> list = new ArrayList<>();
list.add(obj1);
list.add(obj2);
list.add(obj3);
int[] count = jdbcTemplate.batchUpdate(sql, list);
System.out.println("更新的记录条数是:" + Arrays.toString(count));
}
@Test
void batchDelete() {
String sql = "delete from article_detail where id = ?";
Object[] obj1 = {4};
Object[] obj2 = {5};
Object[] obj3 = {3};
List<Object[]> list = new ArrayList<>();
list.add(obj1);
list.add(obj2);
list.add(obj3);
int[] count = jdbcTemplate.batchUpdate(sql, list);
System.out.println("删除的记录条数是:" + Arrays.toString(count));
}
}
@SpringBootTest
class JdbcTemplateApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void queryOneObject(){
String sql = "select * from article where id = ?";
Article article = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Article.class), 1);
System.out.println(article);
}
@Test
void queryOneOValue(){
String sql = "select count(*) from article";
Long count = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println("查询到的记录条数 =====> " + count);
}
}
@SpringBootTest
class JdbcTemplateApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void queryMulObject(){
String sql = "select * from article";
List<Article> articles = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Article.class));
System.out.println(articles);
}
}
@SpringBootTest
class JdbcTemplateApplicationTests {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void testQueryRowMapper() {
String sql = "select * from article where id = 1";
Article article = jdbcTemplate.execute(sql, new PreparedStatementCallback<Article>() {
@Override
public Article doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
Article article = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
var id = rs.getInt("id");
var userId = rs.getInt("user_id");
var title = rs.getString("title");
var summary = rs.getString("summary");
var readCount = rs.getInt("read_count");
var createTime = new Timestamp(rs.getTimestamp("create_time").getTime()).toLocalDateTime();
var updateTime = new Timestamp(rs.getTimestamp("update_time").getTime()).toLocalDateTime();
article = new Article(id, userId, summary, title, readCount, createTime, updateTime);
}
return article;
}
});
System.out.println(article);
}
}
NameParameterJdbcTemplate 能够接受命名的参数,通过具名的参数提供代码的可读性。NameParameterJdbcTemplate 使用的是参数索引的方式。
在使用模板的位置上注入 NameParameterJdbcTemplate 对象,编写 SQL 语句,在 SQL 中Where 部分“:命名参数”。调用 NameParameterJdbcTemplate 的诸如 query,queryForObject,execute,update等时,将参数封装到 Map 中。
@SpringBootTest
class JdbcTemplateApplicationTests {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Test
void testNameQuery(){
String sql = "select count(*) as ct from article where user_id = :uid and read_count > :num";
Map<String, Object> map = new HashMap<>();
map.put("uid", 2101);
map.put("num", 0);
Long count = namedParameterJdbcTemplate.queryForObject(sql, map, Long.class);
System.out.println(count);
}
}
@SpringBootTest
class JdbcTemplateApplicationTests {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Test
void testNameQuery(){
String sql = "select a.*, d.article_id, d.content from article a join article_detail d on a.id = d.article_id where d.id = :id";
Map<String, Object> param = new HashMap<>();
param.put("id", 1);
Map<String, Object> objectMap = namedParameterJdbcTemplate.queryForMap(sql, param);
objectMap.forEach(( key, value)->{
System.out.println(key + "---->" + value);
});
}
}
@SpringBootTest
class JdbcTemplateApplicationTests {
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Test
void testNameQuery(){
String sql = "select a.*, d.article_id, d.content from article a join article_detail d on a.id = d.article_id where d.id = :id";
Map<String, Object> param = new HashMap<>();
param.put("id", 1);
ArticleAndDetail articleAndDetail = namedParameterJdbcTemplate.queryForObject(sql, param, new BeanPropertyRowMapper<>(ArticleAndDetail.class));
System.out.println(articleAndDetail);
}
}