十一 . Springboot-Jdbc

本文介绍了如何在SpringBoot项目中整合JDBC进行数据库操作,包括项目搭建、依赖配置、YAML配置、代码编写等步骤,并提供了具体的示例代码。

SpringBoot的数据访问层都是封装在可以直接使用jdbc

11.1 步骤分析

1 准备一个springboot项目
	略过
2 pom导入对应stater
3 application.yml配置
4 入口类
5 写代码测试

11.2 pom.xml

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

11.3 application.yml

在application.properties文件中配置mysql连接配置文件
########################################################
###datasource
########################################################
spring.datasource.url = jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

11.4 入口类

11.5 代码测试

11.5.1 表设计

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50728
Source Host           : localhost:3306
Source Database       : mytest

Target Server Type    : MYSQL
Target Server Version : 50728
File Encoding         : 65001

Date: 2020-04-04 23:20:48
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for department
-- ----------------------------
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of department
-- ----------------------------
INSERT INTO `department` VALUES ('101', 'IT部');
INSERT INTO `department` VALUES ('102', '销售部');

-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `email` varchar(30) DEFAULT NULL,
  `sex` int(2) DEFAULT NULL,
  `birth` datetime DEFAULT NULL,
  `department_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of employee
-- ----------------------------
INSERT INTO `employee` VALUES ('101', '王小八', 'ba@qq.com', '1', '2020-03-29 11:48:51', '101');
INSERT INTO `employee` VALUES ('102', '小花', 'hua@qq.com', '0', '2020-03-29 16:53:03', '101');

11.5.2 代码测试

@RestController
@RequestMapping("/jdbc")
public class JDBCController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/findAll")
    public List<Map<String, Object>> findAll(){
        String sql = "select * from employee";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    @GetMapping("/save")
    public String save(){
        String sql = "INSERT INTO employee (name,email,sex,birth,department_id) VALUES(?,?,?,?,?)";
        jdbcTemplate.update(sql,"小花","hua@qq.com",0,new Date(),101);
        return "success";
    }
    @GetMapping("/update")
    public String update(){
        String sql = "update employee set name=?,email=?,sex=?,birth=?,department_id=? where id= ?";
        jdbcTemplate.update(sql,"小花儿","huaxx@qq.com",0,new Date(),101,103);
        return "success";
    }
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id")Integer id){
        String sql = "delete from employee where id=?";
        jdbcTemplate.update(sql,id);
        return "success";
    }
}

11.6 小结

​ 本章节讲了Springboot-jdbc的实现

### 配置 `spring.application.name` 和数据源属性 在 Spring Boot 应用中,`spring.application.name` 和数据源属性通常在 `application.yml` 或 `application.properties` 文件中进行配置。`application.yml` 提供了更清晰的层次结构和更好的可读性,适合管理复杂的配置信息[^3]。 #### 配置 `spring.application.name` `spring.application.name` 用于定义应用程序的名称,该名称在服务注册与发现(如 Spring Cloud)中会被使用。在 `application.yml` 中配置方式如下: ```yaml spring: application: name: my-springboot-app ``` 此配置将应用程序名称设置为 `my-springboot-app`,便于识别和管理微服务架构中的各个服务[^1]。 #### 配置数据源属性 Spring Boot 提供了多种方式来配置数据源,推荐使用 HikariCP 作为连接池实现,因其性能优异且配置简单。以下是一个典型的数据库连接配置示例: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/mydatabase username: root password: password driver-class-name: com.mysql.cj.jdbc.Driver hikari: maximum-pool-size: 10 minimum-idle: 5 idle-timeout: 30000 max-lifetime: 1800000 connection-timeout: 30000 pool-name: MyHikariPool ``` 上述配置中,`url`、`username` 和 `password` 分别指定了数据库的连接地址、用户名和密码;`driver-class-name` 指定了数据库驱动类;`hikari` 下的配置项用于调整连接池的行为,如最大连接数、空闲超时时间等[^2]。 #### 使用 Profile 实现多环境配置 为了支持多环境(如开发、测试、生产)配置,可以在 `application.yml` 中使用 `spring.profiles.active` 来指定当前激活的环境,并通过 `application-{profile}.yml` 文件管理不同环境下的配置。例如: ```yaml spring: profiles: active: dev ``` 然后在 `application-dev.yml` 中配置开发环境的数据源信息: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/mydatabase_dev username: devuser password: devpassword ``` 这种方式可以有效隔离不同环境的配置,避免配置冲突,提升开发和部署效率[^3]。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值