天天看點

Spring Boot入門(2)使用MySQL資料庫

介紹

  本文将介紹如何在Spring項目中連接配接、處理MySQL資料庫。

  該項目使用Spring Data JPA和Hibernate來連接配接、處理MySQL資料庫,當然,這僅僅是其中一種方式,你也可以使用Spring JDBC或者MyBatis.

  Spring Data JPA是Spring Data的一個子項目,主要用于簡化資料通路層的實作,使用Spring Data JPA可以輕松實作增删改查、分頁、排序等。Spring Data擁有很多子項目,除了Spring Data Jpa外,還有如下子項目。

  • Spring Data Commons
  • Spring Data MongoDB
  • Spring Data Redis
  • Spring Data Solr
  • Spring Data Gemfire
  • Spring Data REST
  • Spring Data Neo4j

  Hibernate是一個開放源代碼的對象關系映射架構,它對JDBC進行了非常輕量級的對象封裝,它将POJO與資料庫表建立映射關系,是一個全自動的ORM架構,Hibernate可以自動生成SQL語句,自動執行,使得Java程式員可以随心所欲的使用對象程式設計思維來操縱資料庫。 Hibernate可以應用在任何使用JDBC的場合,既可以在Java的用戶端程式使用,也可以在Servlet/JSP的Web應用中使用,最具革命意義的是,Hibernate可以在應用EJB的J2EE架構中取代CMP,完成資料持久化的重任。

  本文将介紹如何使用Spring Data JPA和Hibernate來連接配接、處理MySQL資料庫。

準備

  首先我們需要對MySQL做一些準備處理。我們将要在MySQL中建立db_example資料庫,并建立springuser使用者,擁有對db_example資料庫的所有操作權限。打開MySQL , 輸入以下指令:

mysql> create database db_example; -- 建立新資料庫db_example
mysql> create user 'springuser'@'localhost' identified by 'pwd123'; -- 建立新使用者springuser,密碼為pwd123
mysql> grant all on db_example.* to 'springuser'@'localhost'; -- 給予springuser使用者對db_example資料庫的所有操作權限           

Spring Boot程式

Step1. 建立項目spring_mysql, 以及項目布局:

mkdir spring_mysql
cd ./spring_mysql
touch build.gradle
mkdir -p src/main/java
mkdir -p src/main/resources
mkdir -p src/test/java
mkdir -p src/test/resources           

Step2 編寫build.gradle

  build.gradle代碼如下:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.0.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-accessing-data-mysql'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")

    // JPA Data (We are going to use Repositories, Entities, Hibernate, etc...)
    compile 'org.springframework.boot:spring-boot-starter-data-jpa'

    // Use MySQL Connector-J
    compile 'mysql:mysql-connector-java'

    testCompile('org.springframework.boot:spring-boot-starter-test')
}           

在上述Spring Boot項目中,主要使用spring-boot-starter-web ,spring-boot-starter-data-jpa和mysql:mysql-connector-java來實作在Web端操作MySQL .

Step3 配置屬性檔案

  建立src/main/resources/application.properties檔案,配置相關屬性,代碼如下:

spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=pwd123           

在上述代碼中,主要的資料庫操作為建立(create),因為資料庫中實作不存在相應的表格。使用MySQL的localhost伺服器的3306端口的db_example資料庫,并設定使用者名和密碼。

Step4 編寫Java檔案

  建立src/main/java/hello檔案夾(package),在該檔案夾下建立User.java,Hibernate會将該entity類自動轉化成資料庫中的表格。User.java的完整代碼如下:

package hello;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity // This tells Hibernate to make a table out of this class
public class User {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;

    private String name;

    private String email;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}           

  在上述檔案夾中建立UserRepository.java,其代碼如下:

package hello;

import org.springframework.data.repository.CrudRepository;

import hello.User;

// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete

public interface UserRepository extends CrudRepository<User, Long> {

}           

這是repository接口, 它将會被Spring中的bean中自動執行。

  在上述檔案夾中建立MainController.java,代碼如下:

package hello;

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

import hello.User;
import hello.UserRepository;

@Controller    // This means that this class is a Controller
@RequestMapping(path="/demo") // This means URL's start with /demo (after Application path)
public class MainController {
    @Autowired // This means to get the bean called userRepository
               // Which is auto-generated by Spring, we will use it to handle the data
    private UserRepository userRepository;

    @GetMapping(path="/add") // Map ONLY GET Requests
    public @ResponseBody String addNewUser (@RequestParam String name
            , @RequestParam String email) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepository.save(n);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return userRepository.findAll();
    }
}           

這是Spring應用的新控制器(Controller)。

  在上述檔案夾中建立Application.java,代碼如下:

package hello;

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

這是該Spring Boot項目的主要程式入口。

Step5 建立可執行jar包

cd spring_mysql
gradle build           

執行完畢後,會在build/libs檔案夾下生成gs-accessing-data-mysql-0.1.0.jar .

運作及測試

  使用以下指令啟動該Spring Boot項目

java -jar build/libs/gs-accessing-data-mysql-0.1.0.jar           

  在浏覽器端測試,輸入以下網址:

localhost:8080/demo/add?name=Alex&[email protected]
localhost:8080/demo/add?name=Jclian&[email protected]
localhost:8080/demo/add?name=Bob&[email protected]
localhost:8080/demo/add?name=Cook&[email protected]
localhost:8080/demo/add?name=Mark&[email protected]           

上述程式将會name和email參數的值解析成資料庫中user表中的記錄并儲存,浏覽器界面如下圖:

在浏覽器中輸入網址localhost:8080/demo/all,即可剛看我們我們插入到MySQL中的記錄(JSON格式):

最後我們去MySQL中檢視資料是否插入成功,結果如下圖所示:

結束語

  本文将介紹如何使用Spring Data JPA和Hibernate來連接配接、處理MySQL資料庫。

  本次分享到此結束,接下來還會繼續更新Spring Boot方面的内容,歡迎大家交流~~