幽兰生空谷
--绝世独自开

SpringBoot操作数据库SpringData(一)-集成JDBC

SpringData简介

对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采

用 Spring Data 的方式进行统一处理。

Spring Boot 底层都是采用 Spring Data 的方式进行统一处理各种数据库,Spring Data 也是 Spring 中

与 Spring Boot、Spring Cloud 等齐名的知名项目。

Sping Data 官网:https://spring.io/projects/spring-data

数据库相关的启动器 : 可以参考官方文档:

https://docs.spring.io/spring-boot/docs/current/reference/html/using.html#using.build-systems.starters

集成JDBC

导入测试数据库

CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT CHARACTER SET utf8 */; 
USE `springboot`;

/*Table structure for table `department` */ 
DROP TABLE IF EXISTS `department`; 
CREATE TABLE `department` (
 `id` int(3) NOT NULL AUTO_INCREMENT COMMENT '部门id', 
 `department_name` varchar(20) NOT NULL COMMENT '部门名字', 
 PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=106 DEFAULT CHARSET=utf8; 

/*Data for the table `department` */ 
insert into `department`(`id`,`department_name`) values (101,'技术部'), (102,'销售部'),(103,'售后部'),(104,'后勤部'),(105,'运营部'); 

/*Table structure for table `employee` */ 
DROP TABLE IF EXISTS `employee`; 
CREATE TABLE `employee` ( 
`id` int(5) NOT NULL AUTO_INCREMENT COMMENT '雇员id', 
`last_name` varchar(100) NOT NULL COMMENT '名字', 
`email` varchar(100) NOT NULL COMMENT '邮箱', 
`gender` int(2) NOT NULL COMMENT '性别1 男, 0 女', 
`department` int(3) NOT NULL COMMENT '部门id', 
`birth` datetime NOT NULL COMMENT '生日', 
PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;

/*Data for the table `employee` */ 
insert into `employee`(`id`,`last_name`,`email`,`gender`,`department`,`birth`) 
values (1001,'张三','24736743@qq.com',1,101,'2020-03-06 15:04:33'),
(1002,'李 四','24736743@qq.com',1,102,'2020-03-06 15:04:36'),
(1003,'王 五','24736743@qq.com',0,103,'2020-03-06 15:04:37'),
(1004,'赵 六','24736743@qq.com',1,104,'2020-03-06 15:04:39'),
(1005,'孙 七','24736743@qq.com',0,105,'2020-03-06 15:04:45');

创建测试项目测试数据源

1、我去新建一个项目测试:springboot-data-jdbc ; 引入相应的模块!基础模块 

2、项目建好之后,发现自动帮我们导入了如下的启动器:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

3、编写yaml配置文件连接数据库; 

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

4、配置完这一些东西后,我们就可以直接去使用了,因为SpringBoot已经默认帮我们进行了自动配

置;去测试类测试一下 

package com.itheibai;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class SpringbootDataApplicationTests {
    //DI注入数据源
    @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 , 我们并没有手动配置

我们来全局搜索一下,找到数据源的所有自动配置都在 :DataSourceAutoConfifiguration文件: 

@Import({Hikari.class, Tomcat.class, Dbcp2.class, OracleUcp.class, Generic.class, DataSourceJmxConfiguration.class})
protected static class PooledDataSourceConfiguration {
    protected PooledDataSourceConfiguration() {
    }
}

这里导入的类都在 DataSourceConfifiguration 配置类下,可以看出这里默认使用 HikariDataSource 数据源,而以前版本,如 Spring Boot 1.5 默认使用 org.apache.tomcat.jdbc.pool.DataSource 作为数据源; 

HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat

jdbc 等连接池更加优秀;

可以使用 spring.datasource.type 指定自定义的数据源类型,值为 要使用的连接池实现的完全限定

名。

关于数据源我们并不做介绍,有了数据库连接,显然就可以 CRUD 操作数据库了。但是我们需要先了解

一个对象JdbcTemplate

JdbcTemplate

1、有了数据源(com.zaxxer.hikari.HikariDataSource),然后可以拿到数据库连接(java.sql.Connection),有了连接,就可以使用原生的 JDBC 语句来操作数据库;

2、即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封

装,即JdbcTemplate

3、数据库操作的所有 CRUD 方法都在 JdbcTemplate 中。

4、Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序

员只需自己注入即可使用 

5、JdbcTemplate 的自动配置是依赖 org.springframework.boot.autoconfifigure.jdbc 包下的

JdbcTemplateConfifiguration 类

JdbcTemplate主要提供以下几类方法:

  • execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
  • update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate

方法用于执行批处理相关语句;

  • query方法及queryForXXX方法:用于执行查询相关语句;
  • call方法:用于执行存储过程、函数相关语句。

测试

编写一个Controller,注入 jdbcTemplate,编写测试方法进行访问测试;

package com.itheibai.controller;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/jdbc")
public class JdbcController {
    /**
     * Spring Boot 默认提供了数据源,默认提供了 org.springframework.jdbc.core.JdbcTemplate
     * JdbcTemplate 中会自己注入数据源,用于简化 JDBC操作 * 还能避免一些常见的错误,使用起来也不用再自己来关闭数据库连接
     */
    @Autowired
    JdbcTemplate jdbcTemplate;
    //查询employee表中所有数据
    // List 中的1个 Map 对应数据库的 1行数据
    // Map 中的 key 对应数据库的字段名,value 对应数据库的字段值
    @GetMapping("/list")
    public List<Map<String, Object>> userList(){
        String sql = "select * from employee";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    //新增一个用户
    @GetMapping("/add")
    public String addUser(){
        //插入语句,注意时间问题
        String sql = "insert into employee(last_name, email,gender,department,birth)" +
                "values('黑白一念','123123123@qq.com',1,101,'"+
        new Date().toLocaleString()+ "')";
        jdbcTemplate.update(sql);
        return "addOk";
    }
    //修改用户信息 
    @GetMapping("/update/{id}") 
    public String updateUser(@PathVariable("id") int id){ 
        //插入语句 
        String sql = "update employee set last_name=?,email=? where id="+id; 
        //数据 
        Object[] objects = new Object[2]; 
        objects[0] = "黑白"; 
        objects[1] = "123123123@sina.com"; 
        jdbcTemplate.update(sql,objects); 
        //查询 
        return "updateOk"; 
    }
    //删除用户 
    @GetMapping("/delete/{id}") 
    public String delUser(@PathVariable("id") int id){ 
        //插入语句
        String sql = "delete from employee where id=?"; 
        jdbcTemplate.update(sql,id); 
        //查询 
        return "deleteOk"; 
    }
}

到此,CURD的基本操作,使用 JDBC 就搞定了。

赞(2) 打赏
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《SpringBoot操作数据库SpringData(一)-集成JDBC》
文章链接:https://www.itheibai.com/archives/586
免责声明:根据《计算机软件保护条例》第十七条规定“为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。”您需知晓本站所有内容资源均来源于网络,仅供用户交流学习与研究使用,版权归属原版权方所有,版权争议与本站无关,用户本人下载后不能用作商业或非法用途,需在24个小时之内从您的电脑中彻底删除上述内容,否则后果均由用户承担责任;如果您访问和下载此文件,表示您同意只将此文件用于参考、学习而非其他用途,否则一切后果请您自行承担,如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
本站是非经营性个人站点,所有软件信息均来自网络,所有资源仅供学习参考研究目的,并不贩卖软件,不存在任何商业目的及用途,网站会员捐赠是您喜欢本站而产生的赞助支持行为,仅为维持服务器的开支与维护,全凭自愿无任何强求。

评论 抢沙发

评论前必须登录!

 

养成“打赏”的好习惯,从我做起!

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册