1. 程式人生 > >Spring Boot 2.x連線MySQL資料庫

Spring Boot 2.x連線MySQL資料庫

上篇 只需兩步!Eclipse+Maven快速構建第一個Spring Boot專案 已經構建了一個Spring Boot專案,本文在此基礎上進行連線MySQL資料庫的操作。

1. pom.xml新增依賴

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

2. application.properties新增資料庫配置

spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true

 如果資料庫連線寫成spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot ,由於MySQL版本的問題,可能會有以下的錯誤,在後面加上“?serverTimezone=GMT%2B8”,設定下時區,解決。

 設定驅動,spring.datasource.driver-class-name=com.mysql.jdbc.Driver會有下面紅色的警告資訊。說的是`com.mysql.jdbc.Driver'被棄用了,要使用新的驅動`com.mysql.cj.jdbc.Driver',改成`com.mysql.cj.jdbc.Driver'以後一切正常。

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.

3. 新增實體類

@Entity代表這是一個實體類,@Table(name=”user”)用來對應資料庫中的use表,@Id用來表達主鍵,@Column(name=”id”)表明一個id屬性。 

package com.example.demo.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;
    @Column(name = "username")
    private String userName;
    @Column(name = "password")
    private String passWord;

    public User() {
        super();
    }

    public User(String userName, String passWord) {
        super();
        this.userName = userName;
        this.passWord = passWord;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

}

4. 新增Dao

Dao層主要用來實現對資料庫的增、刪、查、改。 dao只要繼承JpaRepository類就可以,幾乎可以不用寫方法,可以根據方法名來自動的生產SQL,比如findByUserName 會自動生產一個以 userName 為引數的查詢方法。

package com.example.demo.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.demo.domain.User;

public interface UserRepository extends JpaRepository<User, Long> {

    User findByUserName(String userName);

}

5. 新增Controller

package com.example.demo.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.dao.UserRepository;
import com.example.demo.domain.User;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("/getAllUser")
    @ResponseBody
    public List<User> findAll() {
        List<User> list = new ArrayList<User>();
        list = userRepository.findAll();
        return list;
    }

    @RequestMapping("/getByUserName")
    @ResponseBody
    public User getByUserName(String userName) {
        User user = userRepository.findByUserName(userName);
        return user;
    }

}

 對工程新增檔案後工程結構圖:

6. 新建資料庫

新建資料庫mysql://localhost:3306/spring_boot ,必須的一個步驟。Hibernate雖然會自動新建表,但是資料庫還是要手動建好的。

使用Navicat新建本地資料庫,連線名上面右鍵- >新建資料庫 ->填寫資料庫資訊 - > 確定。

在user表中,插入兩條測試資料:

7. 測試

啟動專案。用Postman傳送請求進行測試:

http://localhost:8080//user/getAllUser

 http://localhost:8080//user/getByUserName?userName=Turing