從零開始學(xué)Spring Boot系列-集成MySQL

在Spring Boot中集成MySQL是為了讓開發(fā)者能夠輕松地與MySQL數(shù)據(jù)庫進行交互。本篇文章將指導(dǎo)你如何在Spring Boot 3.2.3項目中使用Gradle來集成MySQL。在此之前,我們需要在Ubuntu 22.04上安裝MySQL 8作為我們的數(shù)據(jù)庫服務(wù)器。

安裝MySQL8

本文是在wsl2上的Ubuntu 22.04上安裝MySQL8.

步驟1: 更新系統(tǒng)

打開終端,并使用以下命令更新系統(tǒng):

 apt update  
 apt upgrade

步驟2: 安裝MySQL

使用以下命令安裝MySQL服務(wù)器:

 apt install mysql-server
20240303162852

步驟3: 啟動MySQL服務(wù)

安裝完成后,啟動MySQL服務(wù), WSL子系統(tǒng)Ubuntu中不包含systemctl命令,使用service命令。

 service mysql start
20240303162955

步驟4: 驗證MySQL安裝

通過以下命令驗證MySQL是否正在運行:

service  mysql status
20240303162812

我們還可以用查看進程

ps -ef | grep mysql
20240303163213

如果一切正常,你將看到MySQL服務(wù)正在運行的信息。

步驟5: 登錄Mysql

第一種登錄方法

root用戶沒有設(shè)置密碼,不能從本地登錄,可以使用sudo命令進入,此時不需要輸入密碼回車即可進入。

mysql -u root -p
20240303163634

第二種登錄方法

MySQL在安裝時會創(chuàng)建很多默認用戶,其中就包含一個 debian-sys-maint,并且創(chuàng)建了該用戶的隨機密碼,存儲該用戶信息的文件位于 /etc/mysql/debian.cnf文件中。


20240303163938

可以利用debian-sys-main用戶登錄MySQL。


20240303164054

步驟6: 更改root用戶密碼

修改 root 密碼 mysql 8.+ 的修改密碼方式

alter user 'root'@'localhost' identified with mysql_native_password by '123456';
flush privileges;
20240303165308

步驟7: 設(shè)置root用戶的遠程訪問

此時root用戶的host屬性仍然是localhost,也就是只能從本地訪問,因此可以將root用戶的訪問權(quán)限由本地改為本地和外部都可以訪問,將host的值由localhost改為 %。

update user set user.host='%' where user.user='root';
flush privileges;
20240303165614

WSL中的Ubuntu子系統(tǒng)訪問可以直接使用127.0.0.1或localhost進行訪問。但是在外部一旦換成Ubuntu真正的IP地址訪問就會報錯。這時還需要修改MySQL配置文件中的相關(guān)配置項 /etc/mysql/mysql.conf.d/mysqld.cnf, 修改 bind-address = 0.0.0.0 。


20240303170902

重啟MySQL后,再次通過IP地址遠程連接。

步驟8: 創(chuàng)建數(shù)據(jù)庫

使用root用戶登錄Mysql,創(chuàng)建一個test的數(shù)據(jù)庫

CREATE DATABASE test DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;

步驟9: 創(chuàng)建數(shù)據(jù)表

創(chuàng)建一張user的表

CREATE TABLE user (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '學(xué)生ID',
name VARCHAR(20) NOT NULL COMMENT '姓名',
email VARCHAR(20)   COMMENT '郵箱',
age  INT  COMMENT '年齡',
remark VARCHAR(80) COMMENT '備注',
PRIMARY KEY (id), /*設(shè)置id為主鍵*/
INDEX (name) /*設(shè)置name為普通索引*/
) ENGINE=InnoDB;

步驟9: 插入數(shù)據(jù)

在user表中插入一條數(shù)據(jù)

INSERT INTO test.user (id, name, email, age, remark) VALUES (1, 'jack', 'jack@163.com', 18, '備注');

添加依賴

首先,你需要在build.gradle文件中添加Spring Boot的starter-data-jpa和MySQL驅(qū)動的依賴。

plugins {
 id 'java'
 id 'org.springframework.boot' version '3.2.3'
 id 'io.spring.dependency-management' version '1.1.4'
}

group = 'cn.daimajiangxin'
version = '0.0.1-SNAPSHOT'

java {
 sourceCompatibility = '17'
 targetCompatibility = '17'
}

 repositories {
        maven { url 'https://maven.aliyun.com/repository/jcenter' }
        maven { url 'https://maven.aliyun.com/repository/google' }
        maven { url 'https://maven.aliyun.com/repository/central' }
        maven { url 'https://maven.aliyun.com/repository/gradle-plugin' }
}

dependencies {
 implementation 'org.springframework.boot:spring-boot-starter-web'
 compileOnly 'org.projectlombok:lombok'
 annotationProcessor 'org.projectlombok:lombok'
 implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
 runtimeOnly 'mysql:mysql-connector-java:8.0.17'
}

配置Spring Boot數(shù)據(jù)源

在src/main/resources/application.properties或application.yaml文件中,配置數(shù)據(jù)源和JPA的相關(guān)設(shè)置。確保使用你在MySQL安裝過程中設(shè)置的root密碼。
application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false&allowPublicKeyRetrieval=true  
spring.datasource.username=root  
spring.datasource.password=your_mysql_root_password
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=true

application.yaml

spring:  
  datasource:  
    url: jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false&allowPublicKeyRetrieval=true  
    username: root  
    password: your_mysql_root_password  
  jpa:
    database-platform: org.hibernate.dialect.MySQLDialect
    show-sql: true

確保將your_database_name和your_mysql_root_password替換為實際的數(shù)據(jù)庫名稱和root用戶的密碼。

創(chuàng)建實體

創(chuàng)建一個簡單的實體類,使用JPA注解來映射到數(shù)據(jù)庫表。

package cn.daimajiangxin.springboot.learning.model;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.Data;

@Data
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    private int age;
    private String remark;
}

創(chuàng)建Repository

創(chuàng)建一個繼承自JpaRepository的接口,以便Spring Data JPA可以自動為你生成實現(xiàn)。

package cn.daimajiangxin.springboot.learning.repository;

import cn.daimajiangxin.springboot.learning.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface  UserRepository extends JpaRepository<User, Long> {
    // 你可以添加自定義查詢方法
}

創(chuàng)建Service

創(chuàng)建一個服務(wù)類來處理業(yè)務(wù)邏輯。

package cn.daimajiangxin.springboot.learning.repository;

import cn.daimajiangxin.springboot.learning.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    // 添加其他業(yè)務(wù)邏輯方法...  
}

創(chuàng)建Controller

創(chuàng)建一個控制器類來處理HTTP請求。

package cn.daimajiangxin.springboot.learning.controller;

import cn.daimajiangxin.springboot.learning.model.User;
import cn.daimajiangxin.springboot.learning.repository.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }
    // 添加其他請求處理方法... 
}

運行應(yīng)用程序

現(xiàn)在,你可以運行你的Spring Boot應(yīng)用程序,并嘗試訪問來http://localhost:8080/users查看所有用戶的列表。

確保你的MySQL數(shù)據(jù)庫正在運行,并且已經(jīng)創(chuàng)建了相應(yīng)的數(shù)據(jù)庫和表,并且插入了數(shù)據(jù)。

總結(jié)

在Spring Boot中集成MySQL是一項簡單而直接的任務(wù),只需添加依賴、配置數(shù)據(jù)源、創(chuàng)建實體、Repository、Service和Controller即可。在本文中,我們學(xué)習(xí)了如何在Spring Boot 3.2.3項目中使用Gradle來集成MySQL,并構(gòu)建了一個簡單的RESTful API來獲取用戶列表。記得根據(jù)你的實際需求來調(diào)整數(shù)據(jù)庫配置和業(yè)務(wù)邏輯。


源文來自:https://daimajiangxin.cn
源碼地址:https://gitee.com/daimajiangxin/springboot-learning

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容