1. 程式人生 > >Spring Boot with Spring-Data-JPA學習案例

Spring Boot with Spring-Data-JPA學習案例

lookup inter name ali src desc mas driver tex

0x01 什麽是Spring Boot?

Spring Boot是用來簡化Spring應用初始搭建以及開發過程的全新框架,被認為是Spring MVC的“接班人”,和微服務緊密聯系在一起。

0x02 為什麽學習Spring Boot?

微服務是如今各大企業都開始火熱使用的技術,而Spring Boot 是學習Spring Cloud的基礎

0x03 Spring Boot 有什麽特點?

1.化繁為簡

2. 備受關註,是下一代框架

3. 微服務的入門級微框架

0x04 Spring Boot 的目標?

為所有的Spring開發提供一個更快速、更廣泛的入門體驗

但是當需求和默認配置偏離時,請盡快放棄使用Spring Boot.

提供一系列的非功能性的特點,是大類項目(如嵌入式服務器,安全,標準,健康檢查,和外部配置)。

絕對不生成代碼,也不需要XML配置。

0x05 準備環境

系統要求

Spring Boot 2.0.0.BUILD-SNAPSHOT 需要JDK1.8 以上和Spring Framework 5.0.2.Release 以上版本

構建支持Maven3.2+ 和Gradle4

Servlet 容器

技術分享圖片

Tips: 也可以將Spring Boot 應用程序部署到任何兼容Servlet 3容器中。

技能要求

熟悉Maven 項目構建

熟悉Spring 註解

熟悉RESful API的理念

IDE

本節課程使用Intellij Idea 作為開發工具

0x06 創建我們的第一個應用程序

接下來我們將會創建一個帶有Spring-Data-JPA功能的Spring-Boot Sample。

1. 打開我們的Intellij IDEA,選擇 ‘Create New Project’

技術分享圖片

2. 選擇Spring Initializr來幫助我們快速創建Spring Boot 程序,JDK 最低1.8,Intializr Service URL保持默認。

技術分享圖片

3. 輸入以下項目配置信息

技術分享圖片

4. 勾選 Web模塊

技術分享圖片

5.SQL 模塊分類中勾選 MySQL 和JPA 模塊

技術分享圖片

6. 接下來工程信息一切保持默認即可

技術分享圖片

7. 修改POM.xml

<?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.xingyun</groupId> <artifactId>spring-boot-with-data-jpa-sample</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring-boot-with-data-jpa-sample</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

8.默認的系統配置文件是application.properties

#server.prot=8080
#server.context-path=/girl

Tips: 我們可以通過這種文件來配置web項目的全局上下文路徑和端口號等,但是這裏我們需要註釋或者刪除掉他們,因為我們有一個更好的方式來實現他們。

9. 配置我們的yml文件

總的配置文件,我們可以通過active:dev|prod 激活我們的開發環境配置或者生產環境配置

application.yml

spring:
  profiles:
    active: dev
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/dbgirl
    username: root
    password:
  jpa:
    hibernate:
      ddl-auto: create
      dialect: MySQLDialect
    show-sql: true

開發環境配置文件

application-dev.yml

server:
  port: 8081
  servlet:
    context-path: /
cupSize: B
age: 18
content: "cupSize=${cupSize},age=${age}"
book:
 name: 第二行代碼
 price: 66.00
 type: 安卓

生產環境配置文件

application-prod.yml

server:
  port: 8086
  servlet:
    context-path: /
cupSize: B
age: 18
content: "cupSize=${cupSize},age=${age}"
book:
 name: 第二行代碼
 price: 66.00
 type: 安卓

10. 代碼結構圖如圖所示

技術分享圖片

10.1 代碼中獲取配置文件中的屬性

我們可以讀取剛才開發環境下配置文件中的定義的常量屬性通過下面的方法

    @Value("${cupSize}")
    private String cupSize;

    @Value("${age}")
    private Integer age;

    @Value("${content}")
    private String content;

    @RequestMapping(value = "/girl",method = RequestMethod.GET)
    public String configurationString(){
        return cupSize+"-----------------"+age+"-------------"+content;
    }
當然如果要配置的常量比較多的時候我們就不能使用上面的方法了,但是我們也有更好的方式實現

10.2 代碼中獲取配置文件中的屬性實體

首先創建實體類 BookProperties.java

package com.xingyun.springbootwithdatajpasample.model;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "book")
public class BookProperties {

    private String name;

    private Double price;

    private String type;

    public String getName() {
        return name;
    }

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

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

Tips: 註意此文件中用到的兩個註解不可省略必須有才行

調用方法如下所示:

@Autowired
    private BookProperties bookProperties;

    @RequestMapping(value = "/book",method = RequestMethod.GET)
    public String bookMethod(){
        return "---------------------"+bookProperties.getName()+bookProperties.getPrice()+bookProperties.getType();
    }

10.3 默認的單個URL映射

  @RequestMapping(value = "/",method = RequestMethod.GET)
    public String home(){
        return "Hello Home Page";
    }

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String say(){
        return "Hello Spring Boot";
    }

10.4 多個URL映射

  @RequestMapping(value = {"/api","/API"},method = RequestMethod.GET)
    public String api(){
        return "Hello API";
    }

10.5 Post 方式訪問

 @RequestMapping(value = "/post",method = RequestMethod.POST)
    public String PostMethod(){
        return "Hello Post Page";
    }

10.6 傳統風格的URL

 @RequestMapping(value = "/url/b",method = RequestMethod.GET)
    public String urlWithQuestion(@RequestParam(value = "id",required = false,defaultValue = "0") Integer uid){
        return "Hello URL -----/url/b?id=***------id="+uid;
    }

訪問請求:

http://127.0.0.1:8081/url/b?id=18

10.7 Restful 風格的URL

 @RequestMapping(value = "/url/a/{id}",method = RequestMethod.GET)
    public String urlWithParams(@PathVariable("id") Integer uid){
        return "Hello URL -----url/a/***------id="+uid;
    }

訪問請求:

http://127.0.0.1:8081/url/a/18

10.8 組合註解

上面我們應該已經發現,既要配置GET/POST又要配置映射路徑很麻煩,因此我們今後可以用組合註解

 @GetMapping(value = "/url/c")
    public String urlWithQuestion2(@RequestParam(value = "id",required = false,defaultValue = "0") Integer uid){
        return "Hello URL -----/url/c?id=***------id="+uid;
    }

訪問請求:

http://127.0.0.1:8081/url/c?id=18

10.9 使用Spring-Data-JPA 組件結合MySQL實現數據庫的增刪改查操作

首先我們需要定義一個實體類Girl.java

package com.xingyun.springbootwithdatajpasample.model;


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


@Entity
public class Girl {

    @Id
    @GeneratedValue
    private Integer id;
    private String girlName;
    private Integer girlAge;

    public Girl() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getGirlName() {
        return girlName;
    }

    public void setGirlName(String girlName) {
        this.girlName = girlName;
    }

    public Integer getGirlAge() {
        return girlAge;
    }

    public void setGirlAge(Integer girlAge) {
        this.girlAge = girlAge;
    }
}

Tips: 特別註意,幾個註解不能少,引入的包路徑千萬別導錯包了,不然會報錯。

然後需要創建一個接口類 GirlRepository.java

package com.xingyun.springbootwithdatajpasample.mmInterface;

import com.xingyun.springbootwithdatajpasample.model.Girl;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface GirlRepository  extends JpaRepository<Girl,Integer>{

    //自定義接口
    public List<Girl> findByGirlAge(Integer girlAge);
}

Tips: 我們需要繼承JpaRepository<Girl,Integer>, 這樣Spring-Data-JPA就會幫我們實現基本的增刪改查。

當然這默認的增刪改查無法滿足我們的實際業務需求,所以我們也可以在這裏擴展我們實現的接口。

增刪改查調用代碼如下所示:

package com.xingyun.springbootwithdatajpasample.controller;


import com.xingyun.springbootwithdatajpasample.mmInterface.GirlRepository;
import com.xingyun.springbootwithdatajpasample.model.Girl;
import com.xingyun.springbootwithdatajpasample.service.GirlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
public class GirlController {

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    /**
     * 查詢所有女生列表
     * @Return
     * */
    @GetMapping("/girls")
    public List<Girl> getGirlList(){
        return girlRepository.findAll();
    }

    /**
     * 添加一個女生
    * */
    @PostMapping("/girls")
    public Girl girlAdd(@RequestParam("girlName") String girlName,@RequestParam("girlAge") Integer girlAge){

        Girl girl=new Girl();
        girl.setGirlName(girlName);
        girl.setGirlAge(girlAge);
        girlRepository.save(girl);
        return girl;
    }

    /**
     * 添加兩個女生
     * */
    @GetMapping("/girls/two")
    public String girlAddTwo(){
        girlService.insertTwo();
        return "success";
    }

    /**
     * 通過Id查詢一個女生
     * */
    @GetMapping("/girls/{id}")
    public Optional<Girl> girlFindById(@PathVariable("id") Integer uid){
         return girlRepository.findById(uid);
    }
    /**
     * 通過年齡查詢一個女生
     * */
    @GetMapping("/girls/age/{girlAge}")
    public List<Girl> girlFindByAge(@PathVariable("girlAge") Integer age){
        return girlRepository.findByGirlAge(age);
    }

    /**
     * 修改一個女生
     */
    @PostMapping(value="/girls/{id}")
    public Girl girlUpdate(@PathVariable("id") Integer uid,@RequestParam("girlName") String girlName,@RequestParam("girlAge") Integer girlAge){
        Girl girl=new Girl();
        girl.setId(uid);
        girl.setGirlName(girlName);
        girl.setGirlAge(girlAge);
        return girlRepository.save(girl);
    }

    /**
     * 刪除一個Id
    * */
    @DeleteMapping(value = "/girls/{id}")
    public void girlDelete(@PathVariable("id") Integer uid){
        girlRepository.deleteById(uid);
    }
}

Tips: 這裏要註意的一點是我這個版本使用的是 Spring-Boot 2.0.0.RELEASE 版本,更新後有個方法做了修改。

public List<Girl> girlFindById(@PathVariable("id") Integer uid){
         return girlRepository.findById(uid);
    }

這個返回集合不再有效,需要改成下面這種:

    @GetMapping("/girls/{id}")
    public Optional<Girl> girlFindById(@PathVariable("id") Integer uid){
         return girlRepository.findById(uid);
    }

11. 可能出現的問題

在初次學習時候可能會出現一些常見的異常,可以移步去我的CSDN博客看這篇文章

細數Spring Boot 中容易中招的那些坑

https://blog.csdn.net/hadues/article/details/79334355

@ConfigurationProperties(prefix = "xxx")的值取出為空

https://blog.csdn.net/hadues/article/details/79123645

真正解決方案:java.lang.ClassNotFoundException: javax.xml.bind.JAXBException

https://blog.csdn.net/hadues/article/details/79188793

12. 學習源碼下載

使用前請在本地創建MySQL數據庫dbgirl

dbgirl.sql

-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: 2018-03-28 03:43:53
-- 服務器版本: 10.1.30-MariaDB
-- PHP Version: 7.2.1

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `dbgirl`
--

-- --------------------------------------------------------

--
-- 表的結構 `girl`
--

CREATE TABLE `girl` (
  `id` int(11) NOT NULL,
  `girl_age` int(11) DEFAULT NULL,
  `girl_name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `girl`
--
ALTER TABLE `girl`
  ADD PRIMARY KEY (`id`);

--
-- 在導出的表使用AUTO_INCREMENT
--

--
-- 使用表AUTO_INCREMENT `girl`
--
ALTER TABLE `girl`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

調用參考readme.txt

使用前需啟動My SQL數據庫
MySQL

default username:root

default password:

1. http://127.0.0.1:8081/

2. http://127.0.0.1:8081/hello

3. http://127.0.0.1:8081/girl

4.http://127.0.0.1:8081/book

5.http://127.0.0.1:8081/api
  http://127.0.0.1:8081/API
  Tips: Get 請求,多映射
7.http://127.0.0.1:8081/api
Tips:Post 請求

8.http://127.0.0.1:8081/url/a/18

9.http://127.0.0.1:8081/url/b?id=18

10.http://127.0.0.1:8081/url/c?id=18

 Tips:組合註解  @GetMapping(value = "/url/c")

11.http://127.0.0.1:8081/girls/

  Tips:Get 獲取所有女生列表

12. http://127.0.0.1:8081/girls/

 Tips: Post girlName girlAge 添加一個女生

 13.http://127.0.0.1:8081/girls/two

 Tips:添加兩個女生

 14.根據Id 查詢女生
  http://127.0.0.1:8081/girls/1

  15.根據年齡查詢女生
  http://127.0.0.1:8081/girls/age/16

  16. http://127.0.0.1:8081/girls/1

  Tips:girlName girlAge Post 根據Id修改一個女生

  17.http://127.0.0.1:8081/girls/1

  Tips:Delete 請求根據id刪除一個女生

  創建數據庫bean時候切記不要導錯包名

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

本課程所有源碼下載地址:https://github.com/geekxingyun/JavaEE-Framework-Sample/tree/master/spring-boot-with-data-jpa-sample

Spring Boot with Spring-Data-JPA學習案例