SpringBoot零基础入门初级篇(三)
这个项目主要是利用SpringBoot+Hibernate实现对数据库的增、查。项目看起来虽然简单,但配置起来还是比较吃力,有许多的细节需要注意,现在我做一个笔记以纪念我遇到的所有问题。一个号称五分钟的项目(严重怀疑雷童鞋说的话可信度为0) 活活做了两小时,自己搭建环境、在小伙伴的帮助下排错,学习IDEA调试、使用postman软件进行前端模拟,收获满满~在排错上感觉自己进步了,打卡~
感谢在学习路上给我指导的所有伙伴~
1. 概述
-
目的:在SpringBoot框架下使用MySQL访问数据
本指南将引导您完成创建与MySQL数据库连接的Spring应用程序的过程,而不是内存中的嵌入式数据库,所有其他指南和许多示例应用程序都使用该数据库。 它使用Spring Data JPA来访问数据库,但这只是众多可能选择中的一种(例如,您可以使用普通的Spring JDBC)。
-
创建一个MySQL数据库,构建一个Spring应用程序并将其与新创建的数据库连接。
-
Maven Gradle 区别,本文使用maven构建项目。
2.实现步骤
- 创建一个maven项目,如下。
- 在实际做的时候很多地方均与官网配置不同,新手要特别注意。
代码如下:
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);
}
}
MainController.java
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
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;
@PostMapping(path="/add") // if use @GetMapping, Map ONLY GET Requests.
public @ResponseBody String addNewUser (@RequestParam String name
, @RequestParam Integer age) {
// @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.setAge(age);
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();
}
}
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 Integer age;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
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, Integer> {
}
application.properties
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/ytt?3useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=admin
spring.jpa.hibernate.use-new-id-generator-mappings=false
#禁用OSIV(open Session in view)
spring.jpa.open-in-view=false
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>org.springframework</groupId>
<artifactId>gs-mysql-data</artifactId>
<version>0.1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA Data (We are going to use Repositories, Entities, Hibernate, etc...) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Use MySQL Connector-J -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 至此,IDEA中的所有配置均已经完成。
- 数据库使用本地MySQL数据库,数据库名为ytt,表名为User,表中的字段等详细信息如下:
至此,项目的所有开发步骤已经完成。
3. 代码解读–关于我遇到的坑
- 这个User类的类名与表名是一致的,如果表名不为User一定会报错。
- 第一个框中的ytt表示数据库名,根据需要更改。
jdbc:mysql://localhost:3306/ytt
-
useUnicode=true&characterEncoding=utf8
配置编码方式 -
serverTimezone=GMT%2B8
配置时区防止使用MySQL时报错报错类型:The server time zone value ‘�й���ʱ��’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
-
spring.jpa.hibernate.use-new-id-generator-mappings=false
springboot 1.5.9.RELEASE 升级至 2.0.5.RELEASE时,spring-boot-starter-data-jpa使用了hibernate5。解决 Table ‘ytt.hibernate_sequence’ doesn’t exist的错误。
-
#禁用OSIV(open Session in view)
spring.jpa.open-in-view=false
4. 运行测试
4.1 直接使用浏览器进行测试
- 测试add方法
- 在浏览器中输入
http://localhost:8080/demo/add?name=First&age=11
并回车
- 运行报错,估计是错误使用
@PostMapping(path="/add")
造成提交数据的方式有问题,浏览器这样的提交方式属于get方法。
解决: 将@PostMapping(path="/add")
改为@GetMapping(path="/add")
。
完美解决
2. 测试all方法
- 在浏览器中输入
http://localhost:8080/demo/add?name=First&age=11
并回车
4.2 使用Postman模拟前端进行测试
注意: 将@GetMapping(path="/add")
改为@PostMapping(path="/add")
。
- 如图。
2. 点击send
3. 查询
4. 使用Postman查询