• Spring Boot JDBC访问数据库(十二)


            我们将学习如何在 Spring Boot 中使用 JDBC 进行数据访问。

    一、JDBC使用配置

    1 导入JDBC场景启动器

            Spring Boot 将日常企业应用研发中的各种场景都抽取出来,做成一个个的场景启动器(Starter),场景启动器中整合了该场景下各种可能用到的依赖,让用户摆脱了处理各种依赖和配置的困扰。
            想要在 Spring  Boot 中使用 JDBC 进行数据访问,第一步就是要在 pom.xml 中导入 JDBC 场景启动器:spring-boot-starter-data-jdbc,代码如下:

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-data-jdbcartifactId>
    4. dependency>

            查看 spring-boot-starter-data-jdbc 的依赖树,可以看到,该场景启动器默认引入了一个数据源:HikariCP,如下图所示:

    2 导入数据库驱动

            JDBC 的场景启动器中并没有导入数据库驱动,我们需要根据自身的需求引入所需的数据库驱动。例如,访问 MySQL 数据库时,需要导入 MySQL 的数据库驱动:mysql-connector-java,示例代码如下:

    1. <dependency>
    2. <groupId>mysqlgroupId>
    3. <artifactId>mysql-connector-javaartifactId>
    4. <scope>runtimescope>
    5. dependency>

    注意:Spring Boot 默认为数据库驱动程序做了版本仲裁,所以我们在导入数据库驱动时,可以不再声明版本。需要注意的是,数据库驱动的版本必须与数据库的版本相对应。 

    3 导入Web场景启动器

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-webartifactId>
    4. dependency>

    4 在配置文件中配置数据库信息

    在application.xml配置文件中配置数据源:

    1. #数据源连接信息
    2. spring:
    3. datasource:
    4. username: root
    5. password: 12345
    6. url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8
    7. driver-class-name: com.mysql.cj.jdbc.Driver

    关于Web场景启动器可以参考我的另一篇博客:

    Spring Boot spring-boot-starter-web(九)_人……杰的博客-CSDN博客

    二、项目举例

    1 项目框架

     2 代码实现

    MainApplication.java:

    1. package com.xj.main;
    2. import org.springframework.boot.SpringApplication;
    3. import org.springframework.boot.autoconfigure.SpringBootApplication;
    4. import org.springframework.context.annotation.ComponentScan;
    5. @ComponentScan("com.xj")
    6. @SpringBootApplication
    7. public class MainApplication {
    8. public static void main(String[] args) {
    9. SpringApplication.run(MainApplication.class, args);
    10. }
    11. }

    User.java:

    1. package com.xj.entity;
    2. public class User {
    3. private Long id;
    4. //姓名
    5. private String name;
    6. //性别
    7. private String gender;
    8. //年龄
    9. private Integer age;
    10. //无参构造方法
    11. public User(){}
    12. //无参构造方法
    13. public User(Integer age){
    14. this.age = age;
    15. }
    16. //有参构造方法
    17. public User(String name, String gender, Integer age){
    18. this.name = name;
    19. this.gender = gender;
    20. this.age = age;
    21. }
    22. public Long getId() {
    23. return id;
    24. }
    25. public void setId(Long id) {
    26. this.id = id;
    27. }
    28. public String getName() {
    29. return name;
    30. }
    31. public void setName(String name) {
    32. this.name = name;
    33. }
    34. public String getGender() {
    35. return gender;
    36. }
    37. public void setGender(String gender) {
    38. this.gender = gender;
    39. }
    40. public Integer getAge() {
    41. return age;
    42. }
    43. public void setAge(Integer age) {
    44. this.age = age;
    45. }
    46. @Override
    47. public String toString() {
    48. return "User[ID:" + id + ", name:"+ name+", gender:" + gender + ", age:" + age + "]";
    49. }
    50. }

    JdbcController.java:

    1. package com.xj.controller;
    2. import com.xj.entity.User;
    3. import org.springframework.jdbc.core.BeanPropertyRowMapper;
    4. import org.springframework.jdbc.core.JdbcTemplate;
    5. import org.springframework.stereotype.Controller;
    6. import org.springframework.web.bind.annotation.*;
    7. import java.util.List;
    8. @ResponseBody
    9. @Controller
    10. @RequestMapping("/jdbc")
    11. public class JdbcController {
    12. private final JdbcTemplate template;
    13. public JdbcController(JdbcTemplate template) {
    14. this.template = template;
    15. }
    16. @GetMapping
    17. public List queryAllUser(){
    18. //查询所有用户
    19. String sql = "select * from user_table";
    20. return template.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(User.class));
    21. }
    22. @GetMapping("/{id}")
    23. public User getUserById(@PathVariable Long id){
    24. //根据主键查询一个用户
    25. String sql = "select * from user_table where ID = ?";
    26. return template.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(User.class));
    27. }
    28. @PostMapping
    29. public int addUser(@RequestBody User user){
    30. //添加用户
    31. String sql = "insert into user_table(name, gender, age) value(?, ?, ?)";
    32. return template.update(sql, user.getName(), user.getGender(), user.getAge());
    33. }
    34. @PutMapping("/{name}")
    35. public int editUserByName(@PathVariable String name,@RequestBody User user){
    36. //根据姓名修改用户
    37. String sql = "update user_table set age = ? where name = ?";
    38. return template.update(sql, user.getAge(), name);
    39. }
    40. @DeleteMapping("/{id}")
    41. public int deleteUserById(@PathVariable Long id){
    42. //根据ID删除用户
    43. String sql = "delete from user_table where id = ?";
    44. return template.update(sql, id);
    45. }
    46. }

    JdbcTest.java:

    1. package com.xj.main;
    2. import com.xj.entity.User;
    3. import org.junit.jupiter.api.Test;
    4. import org.slf4j.Logger;
    5. import org.slf4j.LoggerFactory;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.boot.test.context.SpringBootTest;
    8. import org.springframework.boot.test.web.client.TestRestTemplate;
    9. import org.springframework.boot.web.server.LocalServerPort;
    10. import org.springframework.core.ParameterizedTypeReference;
    11. import org.springframework.http.HttpMethod;
    12. import org.springframework.http.ResponseEntity;
    13. import org.springframework.jdbc.core.JdbcTemplate;
    14. import javax.sql.DataSource;
    15. import java.sql.SQLException;
    16. import java.util.List;
    17. @SpringBootTest(classes = MainApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    18. public class JdbcTest {
    19. private static final Logger log = LoggerFactory.getLogger(JdbcTest.class);
    20. //数据源组件
    21. @Autowired
    22. DataSource dataSource;
    23. //用于访问数据库的组件
    24. @Autowired
    25. JdbcTemplate jdbcTemplate;
    26. @Autowired
    27. private TestRestTemplate restTemplate;
    28. @LocalServerPort
    29. private int port;
    30. //连接测试
    31. @Test
    32. void contextLoads() throws SQLException {
    33. System.out.println("默认数据源为:" + dataSource.getClass());
    34. System.out.println("数据库连接实例:" + dataSource.getConnection());
    35. //访问数据库
    36. Integer i = jdbcTemplate.queryForObject("SELECT count(*) from `user_table`", Integer.class);
    37. System.out.println("user 表中共有" + i + "条数据。");
    38. }
    39. @Test
    40. void testJdbc() throws SQLException{
    41. //查询所有用户
    42. // TODO 如果是返回的集合,要用 exchange 而不是 getForEntity ,后者需要自己强转类型
    43. ResponseEntity> response2 = restTemplate.exchange("http://localhost:" + port + "/jdbc", HttpMethod.GET, null, new ParameterizedTypeReference>() {
    44. });
    45. final List body = response2.getBody();
    46. log.info("[查询所有] - [{}]\n", body);
    47. //根据主键查询一个用户
    48. Long userId = body.get(0).getId();
    49. ResponseEntity response3 = restTemplate.getForEntity("http://localhost:" + port + "/jdbc/{id}", User.class, userId);
    50. log.info("[主键查询] - [{}]\n", response3.getBody());
    51. //添加一个用户
    52. restTemplate.postForEntity("http://localhost:" + port + "/jdbc", new User("浮生若梦", "female", 23), Integer.class);
    53. log.info("[添加用户成功]\n");
    54. //根据姓名修改用户
    55. String name = body.get(0).getName();
    56. restTemplate.put("http://localhost:" + port + "/jdbc/{name}", new User(18), name);
    57. log.info("[修改用户成功]\n");
    58. //根据id删除用户
    59. restTemplate.delete("http://localhost:" + port + "/jdbc/{id}", userId);
    60. log.info("[删除用户成功]");
    61. }
    62. }

    application.yml:

    1. #默认配置
    2. server:
    3. port: 8080
    4. #数据源连接信息
    5. spring:
    6. datasource:
    7. username: root
    8. password: 12345
    9. url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8
    10. driver-class-name: com.mysql.cj.jdbc.Driver

    若想和前面的Spring Boot profile文件(六)知识相结合,配置文件application.yml也可以这样写:

    1. #默认配置
    2. server:
    3. port: 8080
    4. spring:
    5. datasource: #数据源连接信息
    6. username: root
    7. password: 12345
    8. url: jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=UTF-8
    9. driver-class-name: com.mysql.cj.jdbc.Driver
    10. profiles:
    11. active: dev #切换配置,指定使用哪个profile
    12. ---
    13. #开发环境
    14. server:
    15. port: 8081
    16. spring:
    17. config:
    18. activate:
    19. on-profile: dev
    20. ---
    21. #测试环境
    22. server:
    23. port: 8082
    24. spring:
    25. config:
    26. activate:
    27. on-profile: test
    28. ---
    29. #生产环境
    30. server:
    31. port: 8083
    32. spring:
    33. config:
    34. activate:
    35. on-profile: prod
    36. logging:
    37. config: classpath:logback-spring.xml #指定使用哪个日志配置文件

    pom.xml:

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0modelVersion>
    6. <groupId>com.xj.studygroupId>
    7. <artifactId>spring-boot-study-projectartifactId>
    8. <version>1.0-SNAPSHOTversion>
    9. <parent>
    10. <groupId>org.springframework.bootgroupId>
    11. <artifactId>spring-boot-starter-parentartifactId>
    12. <version>2.4.5version>
    13. <relativePath/>
    14. parent>
    15. <dependencies>
    16. <dependency>
    17. <groupId>org.springframework.bootgroupId>
    18. <artifactId>spring-boot-starter-webartifactId>
    19. dependency>
    20. <dependency>
    21. <groupId>org.springframework.bootgroupId>
    22. <artifactId>spring-boot-starter-testartifactId>
    23. <scope>testscope>
    24. dependency>
    25. <dependency>
    26. <groupId>org.springframework.bootgroupId>
    27. <artifactId>spring-boot-starter-data-jdbcartifactId>
    28. dependency>
    29. <dependency>
    30. <groupId>org.springframework.bootgroupId>
    31. <artifactId>spring-boot-configuration-processorartifactId>
    32. <optional>trueoptional>
    33. dependency>
    34. <dependency>
    35. <groupId>org.webjarsgroupId>
    36. <artifactId>jqueryartifactId>
    37. <version>3.6.0version>
    38. dependency>
    39. <dependency>
    40. <groupId>org.springframework.bootgroupId>
    41. <artifactId>spring-boot-starter-thymeleafartifactId>
    42. dependency>
    43. <dependency>
    44. <groupId>mysqlgroupId>
    45. <artifactId>mysql-connector-javaartifactId>
    46. <scope>runtimescope>
    47. dependency>
    48. dependencies>
    49. <build>
    50. <plugins>
    51. <plugin>
    52. <groupId>org.springframework.bootgroupId>
    53. <artifactId>spring-boot-maven-pluginartifactId>
    54. <executions>
    55. <execution>
    56. <goals>
    57. <goal>repackagegoal>
    58. goals>
    59. execution>
    60. executions>
    61. plugin>
    62. plugins>
    63. build>
    64. project>

    数据库user_table表:

    1. CREATE TABLE `user_table` (
    2. `ID` bigint(10) NOT NULL AUTO_INCREMENT,
    3. `NAME` varchar(50) DEFAULT NULL COMMENT '姓名',
    4. `GENDER` varchar(10) DEFAULT NULL COMMENT '性别',
    5. `AGE` int(11) DEFAULT NULL COMMENT '年龄',
    6. `LAST_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    7. `CREATE_TIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    8. PRIMARY KEY (`ID`)
    9. ) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8;

     3 运行结果

    数据库user_table表:

    3.1 运行JdbcTest.contextLoads()方法测试数据库连通性

     3.2 运行JdbcTest.testJdbck()方法测试对表user_table增删改查操作

    三、参考

    1.Spring Boot JDBC访问数据库

    2.一起来学SpringBoot | 第五篇:使用JdbcTemplate访问数据库 | 鏖战八方 

  • 相关阅读:
    25张炫酷交互图表,一文入门Plotly
    智能优化算法Matlab源码大礼包领取
    【C++】C/C++内存管理(new和delete详解)
    Python学习:循环语句教程
    golang 解决invalid argument tmp (type interface {}) for len
    【LeetCode热题100】--15.三数之和
    携创教育:2022下半年自考延期省市有哪些?公告是什么?
    从制造到“智造”,看科聪控制系统如何赋能汽车行业智能生产
    MySQL Oracle区别
    个人博客系统
  • 原文地址:https://blog.csdn.net/qq_21370419/article/details/126425599