首页 > 其他分享 >第04章 SpringBoot集成JDBC

第04章 SpringBoot集成JDBC

时间:2024-10-14 11:18:17浏览次数:3  
标签:JDBC SpringBoot 04 spring boot springframework datasource import org

首先,我们新创建一个 “SpringBootJdbcDemo” 的Maven工程。

然后我们修改编码格式以及Maven仓库地址,我们省略这个过程了。

接着我们再添加spring-boot-starter-parent,spring-boot-starter-web,spring-boot-starter-thymeleaf依赖库,然后我们还需要添加本章节要学习的spring-boot-starter-jdbc和mysql-connector-java驱动两个库文件,如下

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>SpringBootJdbcDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.13</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.18</version>
            </plugin>
        </plugins>
    </build>

</project>

我们新添加的依赖库需要下载。下载完毕之后,我们就可以继续创建“Application”的入口类了

package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
    }
}

这个文件基本上也是固定不变的。

接下来,我们就可以对数据库进行操作了。在之前的项目中,我们需要配置DataSource数据源,里面需要配置数据库连接参数。SpringBoot自然也提供了更加方便的使用方式。接下来,我们需要在“resources”资源目录下创建 application.properties 配置文件,我们要在这个文件里面配置数据库连接参数,SpringBoot就会自动从这个配置文件中获取数据库连接参数,如下所示

spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
spring.datasource.username = root
spring.datasource.password = 123456

这里需要提醒大家的,如果你安装的是MySQL8.0的话,我们所需的驱动和配置是不一样的,大家可以自行了解。

Spring JDBC的核心就是JDBCTemplate,有了它就能进行数据库表操作了。Spring Boot 已经自动为我们做好的所有的配置,包括数据源以及JdbcTemplate,我们只需要使用 @Autowired 注解将其注入到其他bean中使用即可。这一些都是SpringBoot遵守 “约定大于配置” 的原则来简化开发流程,接下来,我们就创建一个“StudentDao” 类

package com.demo;

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 StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 查询学生列表
    public List<StudentData> getStudentList(){

        String sql = "select * from student_info order by stu_id asc";
        return jdbcTemplate.query(sql,
                new BeanPropertyRowMapper<StudentData>(StudentData.class), null);
    }

}
package com.demo;

public class StudentData {

    private int stuId;
    private int classId;
    private String stuName;
    private int stuAge;
    private int stuSex;
    private String addTime;

	// 省略get/set方法
}

这样的使用方式,明显是方便快捷了很多。

接下来,我们在“StudentController”中来使用“StudentDao”

package com.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.Map;

@Controller
public class StudentController {

    @Autowired
    private StudentDao studentDao;

    @RequestMapping("/student")
    public String student(Map<String, Object> map){

        List<StudentData> list = studentDao.getStudentList();
        map.put("list", list);
        return "student";
    }
}

接下来,我们在 “resources” 下创建 “templates” 目录,然后继续创建 “student.html” 视图文件

<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>student</title>
</head>
<body>

<div th:each="item:${list}">
    <span th:text="${item.stuName}"></span>
</div>

</body>
</html>

我们使用之前章节的 “Thymeleaf” 模版输出列表数据。关于更多“Thymeleaf” 模版的使用请参考之前章节。接下来,我们在创建一个名称为 “index.html” 工程访问入口文件,请大家注意的是,这个文件是静态文件,需要放置到在 “resources” 下创建 “static” 目录下,如下所示

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>index</title>
</head>
<body>

<a href="/student">student</a>

</body>
</html>

我们工程的文件结构为

接下来,我们就Run当前工程,然后浏览器访问:http://localhost:8080/

剩下的其他数据库操作,我们就不在详细介绍了,更多关于 JdbcTemplate 的使用请参考之前的章节:第四章 Spring集成JDBC-CSDN博客 Spring Boot对我们的帮助主要在于项目前期的搭建工作,具体的业务流程操作,比如数据库操作,视图层数据展示等等,还是需要我们按照之前的方式一点一点完成的,SpringBoot不会在这些方法给我们提供便捷的支持。也就是说,SpringBoot让我们更加专注业务逻辑的研发工作,而其他的工作则给我们提供一个简单的快捷工具化支持。

接下来,我们介绍如何使用 “Druid ” 数据库连接池。Druid 是阿里巴巴开源平台上一个数据库连接池实现。首先我们需要在“pom.xml”中增加“Druid ”的支持,Druid官方已提供starter启动器了

<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid-spring-boot-starter</artifactId>
	<version>1.2.8</version>
</dependency>

接下来,直接修改“application.properties” 文件

spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
spring.datasource.username = root
spring.datasource.password = 123456

与之前相比,仅仅增加了 “spring.datasource.type” 一项内容。

我们重新运行项目,就可以继续访问:http://localhost:8080/

Druid Spring Boot Starter 配置属性的名称完全遵照 Druid,你可以通过 Spring Boot 配置文件来配置Druid数据库连接池和监控,如果没有配置则使用默认值。我们可以简单在 “application.properties” 文件中做几项设置

# 初始化连接数量
spring.datasource.druid.initial-size=10
# 最小线连接数量
spring.datasource.druid.min-idle=10
# 最大连接数量
spring.datasource.druid.max-active=100

我们在“application.properties” 文件中添加几个比较重要的参数设置,参数说明已经在注释中给出了。

更多Druid内容可以参考这里:常见问题 · alibaba/druid Wiki · GitHub

更多 Druid 参数设置请参考这里:DruidDataSource配置 · alibaba/druid Wiki · GitHub

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> 
     <property name="url" value="${jdbc_url}" />
     <property name="username" value="${jdbc_user}" />
     <property name="password" value="${jdbc_password}" />

     <property name="filters" value="stat" />

     <property name="maxActive" value="20" />
     <property name="initialSize" value="1" />
     <property name="maxWait" value="6000" />
     <property name="minIdle" value="1" />

     <property name="timeBetweenEvictionRunsMillis" value="60000" />
     <property name="minEvictableIdleTimeMillis" value="300000" />

     <property name="testWhileIdle" value="true" />
     <property name="testOnBorrow" value="false" />
     <property name="testOnReturn" value="false" />

     <property name="poolPreparedStatements" value="true" />
     <property name="maxOpenPreparedStatements" value="20" />

     <property name="asyncInit" value="true" />
</bean>

我们按照规则将上面的bean设置转换为“application.properties”格式即可。

标签:JDBC,SpringBoot,04,spring,boot,springframework,datasource,import,org
From: https://blog.csdn.net/richieandndsc/article/details/142913489

相关文章

  • aardio入门到精通04-标识符及命名规则、局部变量、成员变量、常量
    标识符、局部变量、名字空间、成员变量、importconsole;//一、标识符/*1)标识符是指编程语言中由起标识作用的英文字母、数字或中文字符、以及下划线组成的命名符号一般用来标识用户或系统定义的数据或方法,例如常量名、变量名、函数名等。2)标识符基本规则: -标识符......
  • MySQL 的 JDBC 编程
    MySQL的JDBC编程使用java代码操作数据库jdbc统一了各种数据库的api准备阶段首先要准备编辑语言的安装:javajdk1.8数据库数据库驱动包:在中央仓库下载搜索MySQL第一个就是MySQLConnector/j下载完成后在IDEA中导入这个包打开IDEA新建一个java项目新建......
  • 097基于java ssm springboot汽车配件销售商城管理系统(源码+文档+运行视频+讲解视频)
    项目技术:Springboot+Maven+Vue等等组成,B/S模式+Maven管理等等。环境需要1.运行环境:最好是javajdk1.8,我们在这个平台上运行的。其他版本理论上也可以。2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA;3.tomcat环境:Tomcat7.x,8.x,9.x版本均可4.硬件环境:windows......
  • 100基于java ssm springboot体检预约系统体检套餐报告体检论坛(源码+文档+运行视频+讲
    项目技术:Springboot+Maven+Vue等等组成,B/S模式+Maven管理等等。环境需要1.运行环境:最好是javajdk1.8,我们在这个平台上运行的。其他版本理论上也可以。2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA;3.tomcat环境:Tomcat7.x,8.x,9.x版本均可4.硬件环境:windows......
  • 101基于java ssm springboot协同过滤算法高考志愿填报系统(源码+文档+运行视频+讲解视
    项目技术:Springboot+Maven+Vue等等组成,B/S模式+Maven管理等等。环境需要1.运行环境:最好是javajdk1.8,我们在这个平台上运行的。其他版本理论上也可以。2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA;3.tomcat环境:Tomcat7.x,8.x,9.x版本均可4.硬件环境:windows......
  • 091基于java ssm springboot考研互助平台系统招生信息交流互动(源码+文档+运行视频+讲
    项目技术:Springboot+Maven+Vue等等组成,B/S模式+Maven管理等等。环境需要1.运行环境:最好是javajdk1.8,我们在这个平台上运行的。其他版本理论上也可以。2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA;3.tomcat环境:Tomcat7.x,8.x,9.x版本均可4.硬件环境:windows......
  • 基于springboot的校园智能垃圾分类平台网站系统java项目
    该校园智能垃圾分类平台网站系统基于SpringBoot构建,致力于提升校园垃圾分类的效率和准确性,促进校园环境的可持续发展。对于学生和教职工来说,系统提供了便捷的使用界面。用户可以在平台上快速查询各种垃圾的分类信息,通过输入垃圾名称或描述,系统能准确告知其所属类别及正......
  • 基于微信小程序+springboot的校园综合服务系统网站java项目
    该校园综合服务系统网站项目结合微信小程序和SpringBoot技术,为校园师生提供便捷、全面的服务。对于学生而言,微信小程序端提供了丰富的功能。学生可以通过小程序查看课程安排、考试时间和成绩等学业信息,方便及时了解自己的学习进度。同时,能够在线进行图书馆书籍借阅预约......
  • 基于协同过滤的就业推荐系统java+springboot的项目
    该就业推荐系统基于Java+SpringBoot构建,利用协同过滤算法实现精准的就业推荐服务。对于求职者而言,系统能够根据他们的个人信息、教育背景、工作经历、技能特长以及求职意向等多维度数据进行分析。通过协同过滤算法,找到与该求职者具有相似特征和职业路径的其他用户群......
  • 基于springboot的协作会话平台网站系统java项目
    基于springboot的协作会话平台网站系统Java项目旨在创建一个高效便捷的在线协作交流环境。该系统支持多用户实时会话,用户可通过文字、语音、视频等多种方式进行沟通交流。具备群组创建功能,方便团队或项目组进行集中讨论和协作,成员可在群组内共享文件、资料等。提供强大......