关于java:从零开始学Spring-Boot系列集成MySQL

6次阅读

共计 5473 个字符,预计需要花费 14 分钟才能阅读完成。

在 Spring Boot 中集成 MySQL 是为了让开发者可能轻松地与 MySQL 数据库进行交互。本篇文章将领导你如何在 Spring Boot 3.2.3 我的项目中应用 Gradle 来集成 MySQL。在此之前,咱们须要在 Ubuntu 22.04 上装置 MySQL 8 作为咱们的数据库服务器。

装置 MySQL8

本文是在 wsl2 上的 Ubuntu 22.04 上装置 MySQL8.

步骤 1: 更新零碎

关上终端,并应用以下命令更新零碎:

 apt update  
 apt upgrade

步骤 2: 装置 MySQL

应用以下命令装置 MySQL 服务器:

 apt install mysql-server

步骤 3: 启动 MySQL 服务

装置实现后,启动 MySQL 服务, WSL 子系统 Ubuntu 中不蕴含 systemctl 命令,应用 service 命令。

 service mysql start

步骤 4: 验证 MySQL 装置

通过以下命令验证 MySQL 是否正在运行:

service  mysql status

咱们还能够用查看过程

ps -ef | grep mysql

如果一切正常,你将看到 MySQL 服务正在运行的信息。

步骤 5: 登录 Mysql

第一种登录办法

root 用户没有设置明码,不能从本地登录,能够应用 sudo 命令进入,此时不须要输出明码回车即可进入。

mysql -u root -p

第二种登录办法

MySQL 在装置时会创立很多默认用户,其中就蕴含一个 debian-sys-maint,并且创立了该用户的随机明码,存储该用户信息的文件位于 /etc/mysql/debian.cnf 文件中。

能够利用 debian-sys-main 用户登录 MySQL。

步骤 6: 更改 root 用户明码

批改 root 明码 mysql 8.+ 的批改明码形式

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

步骤 7: 设置 root 用户的近程拜访

此时 root 用户的 host 属性依然是 localhost,也就是只能从本地拜访,因而能够将 root 用户的拜访权限由本地改为本地和内部都能够拜访,将 host 的值由 localhost 改为 %。

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

WSL 中的 Ubuntu 子系统拜访能够间接应用 127.0.0.1 或 localhost 进行拜访。然而在内部一旦换成 Ubuntu 真正的 IP 地址拜访就会报错。这时还须要批改 MySQL 配置文件中的相干配置项 /etc/mysql/mysql.conf.d/mysqld.cnf, 批改 bind-address = 0.0.0.0。

重启 MySQL 后,再次通过 IP 地址近程连贯。

步骤 8: 创立数据库

应用 root 用户登录 Mysql,创立一个 test 的数据库

CREATE DATABASE test DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;

步骤 9: 创立数据表

创立一张 user 的表

CREATE TABLE user (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '学生 ID',
name VARCHAR(20) NOT NULL COMMENT '姓名',
email VARCHAR(20)   COMMENT '邮箱',
age  INT  COMMENT '年龄',
remark VARCHAR(80) COMMENT '备注',
PRIMARY KEY (id), /* 设置 id 为主键 */
INDEX (name) /* 设置 name 为一般索引 */
) ENGINE=InnoDB;

步骤 9: 插入数据

在 user 表中插入一条数据

INSERT INTO test.user (id, name, email, age, remark) VALUES (1, 'jack', 'jack@163.com', 18, '关注公众号:代码匠心');

增加依赖

首先,你须要在 build.gradle 文件中增加 Spring Boot 的 starter-data-jpa 和 MySQL 驱动的依赖。

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 数据源

在 src/main/resources/application.properties 或 application.yaml 文件中,配置数据源和 JPA 的相干设置。确保应用你在 MySQL 装置过程中设置的 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 替换为理论的数据库名称和 root 用户的明码。

创立实体

创立一个简略的实体类,应用 JPA 注解来映射到数据库表。

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;
}

创立 Repository

创立一个继承自 JpaRepository 的接口,以便 Spring Data JPA 能够主动为你生成实现。

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> {// 你能够增加自定义查询方法}

创立 Service

创立一个服务类来解决业务逻辑。

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();
    }

    // 增加其余业务逻辑办法...  
}

创立 Controller

创立一个控制器类来解决 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();
    }
    // 增加其余申请解决办法... 
}

运行应用程序

当初,你能够运行你的 Spring Boot 应用程序,并尝试拜访来 http://localhost:8080/users 查看所有用户的列表。

确保你的 MySQL 数据库正在运行,并且曾经创立了相应的数据库和表, 并且插入了数据。

总结

在 Spring Boot 中集成 MySQL 是一项简略而间接的工作,只需增加依赖、配置数据源、创立实体、Repository、Service 和 Controller 即可。在本文中,咱们学习了如何在 Spring Boot 3.2.3 我的项目中应用 Gradle 来集成 MySQL,并构建了一个简略的 RESTful API 来获取用户列表。记得依据你的理论需要来调整数据库配置和业务逻辑。


我是代码匠心,和我一起学习更多精彩常识!!!扫描二维码!关注我,实时获取推送。

源文来自:https://daimajiangxin.cn

正文完
 0