0x01 什么是Spring Boot?

0x02 为什么学习Spring Boot?

微服务是如今各大企业都开始火热使用的技术,而Spring Boot 是学习Spring Cloud的基础

0x03 Spring Boot 有什么特点?

0x04 Spring Boot 的目标?

0x05 准备环境

系统要求

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

构建支持Maven3.2+ 和Gradle4

Servlet 容器

Spring Boot with Spring-Data-JPA学习案例-LMLPHP

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

技能要求

IDE

本节课程使用Intellij Idea 作为开发工具

0x06 创建我们的第一个应用程序

接下来我们将会创建一个带有Spring-Data-JPA功能的Spring-Boot Sample。

1. 打开我们的Intellij IDEA,选择 ‘Create New Project’

Spring Boot with Spring-Data-JPA学习案例-LMLPHP

2. 选择Spring Initializr来帮助我们快速创建Spring Boot 程序,JDK 最低1.8,Intializr Service URL保持默认。

Spring Boot with Spring-Data-JPA学习案例-LMLPHP

3. 输入以下项目配置信息

Spring Boot with Spring-Data-JPA学习案例-LMLPHP

4. 勾选 Web模块

Spring Boot with Spring-Data-JPA学习案例-LMLPHP

5.SQL 模块分类中勾选 MySQL 和JPA 模块

Spring Boot with Spring-Data-JPA学习案例-LMLPHP

6. 接下来工程信息一切保持默认即可

Spring Boot with Spring-Data-JPA学习案例-LMLPHP

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.port=8080
#配置应用程序的上下文
server.servlet.context-path=/

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

Spring 2.0 更新变动

Spring Boot with Spring-Data-JPA学习案例-LMLPHP

开发环境配置文件

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. 代码结构图如图所示

Spring Boot with Spring-Data-JPA学习案例-LMLPHP

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 @JsonFormat  Date注解

关于JsonFormat 时间如果希望格式化时间为12小时制的,则使用hh:mm:ss 如果希望格式化时间为24小时制的,则使用HH:mm:ss

    @JsonFormat(pattern = "yyyy-mm-dd HH:ss:mm",locale = "zh",timezone = "GMT+8")//2018-40-07 16:24:40
Date publishedTime;//发表时间
@JsonFormat(pattern = "yyyy-mm-dd hh:ss:mm a",locale = "zh",timezone = "GMT+8")//2018-40-07 04:24:40 下午
Date updatedTime;//修改时间

10.10 使用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/SpringBoot-Sample/spring-boot-with-data-jpa-sample

推荐学习免费视频教程地址:http://www.imooc.com/learn/767

05-11 13:23