SpringBoot 使用 JDBC Template
前题
借助:IntelliJ IDEA
,Maven构建工具
,以及基于SpringBoot 2.3.4
。
官人如需使用 Maven 请阅读教程:Maven 构建工具的下载与安装
官人如需使用 IDEA 请阅读教程:IntelliJ IDEA
更多干货
请参考:Java学习资料
背景
Spring Framework对数据库的操作在JDBC
上面做了深层次的封装
,通过依赖注入功能,可以将DataSource
注册到JdbcTemplate
之中,使我们可以轻易的完成对象关系映射,并有助于规避常见的错误,在SpringBoot中我们可以很轻松的使用它。
使用
目录结构
pom.xml 依赖
Spring JDBC 的依赖包,使用 spring-boot-starter-jdbc
或 spring-boot-starter-data-jpa 将会自动获得HikariCP依赖,此外此项目还用到如下依赖。
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>jdbc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jdbc</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.properties配置文件
在application.properties中添加如下配置。值得注意的是,SpringBoot默认会自动配置DataSource,它将优先采用HikariCP
连接池.
如果没有该依赖的情况则选取tomcat-jdbc,如果前两者都不可用最后选取Commons DBCP2。通过spring.datasource.type属性可以指定其它种类的连接池
server.port=9090
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql:///test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
查看默认数据源:
package com.example.jdbc;
import org.junit.jupiter.api.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 javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@RunWith(SpringRunner.class)
@SpringBootTest
class JdbcApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认数据源
System.out.println(dataSource.getClass());
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
class com.zaxxer.hikari.HikariDataSource
2020-10-18 13:21:21.481 INFO 3412 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2020-10-18 13:21:21.698 INFO 3412 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
HikariProxyConnection@392795843 wrapping com.mysql.cj.jdbc.ConnectionImpl@411c6d44
创建表
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, '测试1', '111', 20);
INSERT INTO `user` VALUES (2, '测试2', '222', 11);
INSERT INTO `user` VALUES (3, '测试3', '333', 25);
INSERT INTO `user` VALUES (4, '测试4', '444', 17);
INSERT INTO `user` VALUES (5, '测试5', '555', 12);
编写User 实体类
package com.example.jdbc.domain;
import lombok.Data;
@Data
public class User {
private Integer id;
private String name;
private String password;
private Integer age;
}
编写DemoController类
package com.example.jdbc.controller;
import com.example.jdbc.domain.User;
import com.example.jdbc.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
import java.util.List;
@Controller
public class DemoController {
@Resource
private UserService userService;
@GetMapping("/demo1")
public String demo1(Model model){
List<User> users = userService.queryAll();
System.out.println(users);
model.addAttribute("user",users);
return "index";
}
}
编写index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<link rel="stylesheet" href="style.css">
<body>
<h1>测试SpringBoot 使用jdbcTemplate</h1>
<ul>
<li th:each="u : ${user}" th:object="${u}">
<div>
<span th:text="*{name}">水果</span>
<span th:text="${u.age}">价格</span>
</div>
</li>
</ul>
</body>
</html>
编写Service 层
package com.example.jdbc.service;
import com.example.jdbc.domain.User;
import java.util.List;
public interface UserService {
List<User> queryAll();
}
package com.example.jdbc.service.impl;
import com.example.jdbc.dao.UserDao;
import com.example.jdbc.domain.User;
import com.example.jdbc.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public List<User> queryAll() {
List<User> users = userDao.queryAll();
return users;
}
}
编写Dao层
package com.example.jdbc.dao;
import com.example.jdbc.domain.User;
import java.util.List;
public interface UserDao {
List<User> queryAll();
}
package com.example.jdbc.dao.impl;
import com.example.jdbc.dao.UserDao;
import com.example.jdbc.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public List<User> queryAll(){
List<User> user =jdbcTemplate.query("select *from user",new BeanPropertyRowMapper<User>(User.class));
return user;
}
}
测试
执行:http://localhost:9090/demo1
总结:
本节只写了JdbcTemplate
的一种操作,详细请参考:JdbcTemplate API文档
待完善…
本教程基于最新的spring-boot-starter-parent:2.3.4RELEASE
编写,目前很多大佬都写过关于SpringBoot的教程了,如有雷同,请多多包涵.