Mysql數據庫這裏要用到Spring-Data-Jpa,它是JPA規範下提供的Repository層的實現,能夠使用Hibernate、OpenJpa等框架進行開發。關於JPA規範,它的全稱
Java Persistence API
(Java持久化API)一個ORM規範,具體實現仍是Hibernate等,JPA爲咱們提供了CRUD的接口。html
更多詳細方法及使用參考官方文檔 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
java
deleteByProperty
Property爲字段屬性名項目根目錄 pom.xml
添加依賴 spring-boot-starter-data-jpa
mysql-connector-java
node
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
複製代碼
application.yml
mysql
datasource
數據源
driver-class-name
驅動名稱username
數據庫用戶名password
數據庫密碼spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbUser?useUnicode=true&characterEncoding=utf-8&useSSL=true
username: root
password: 123456
複製代碼
hibernate
: 相關配置信息有如下幾種類型
ddl-auto:create
: 每次運行加載無論以前是否有數據都會自動建立一個表,會形成數據丟失。ddl-auto:update
: 第一次加載會建立新的數據接口,以後只會在原有表基礎之上進行迭代。ddl-auto:validate
: 驗證類裏面的屬性與表結構是否一致。ddl-auto:create-drop
: 每次退出時刪除。ddl-auto:node
: 默認什麼都不作。show-sql
: 是否打印SQL,在開發時能夠開啓方便調試。database
: 數據庫類型。spring:
jpa:
hibernate:
ddl-auto: update
show-sql: true
database: mysql
複製代碼
GET
: 查詢全部用戶信息GET
: 根據年齡獲取用戶信息POST
: 增長用戶(姓名、年齡)PUT
: 修改用戶DELETE
: 刪除用戶就是建立存儲的User實體(User類)git
是不須要手動去數據庫建立表的,如下建立的User類和定義的屬性會對應到數據庫中的表和字段,這就須要應用jpa的特性了,看下如下註解。github
@Entity
: 表明此類映射爲數據庫的表結構@Id
: 指定一個主鍵@GeneratedValue
: 配置主鍵相關信息
Table
: 使用一個特定的數據庫表來保存主鍵IDENTITY
: 數據庫自動生成AUTO
: 主鍵由程序控制,默認值SEQUENCE
: 經過數據庫的序列產生主鍵, MYSQL
不支持,部分數據庫(Oracle,PostgreSQL,DB2)
支持序列對象User.java
web
@Entity
public class User {
@Id
@GeneratedValue
private Integer id;
private String name;
private Integer age;
public User() {
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
}
複製代碼
建立接口User的數據訪問UserRepository繼承於JpaRepository,能夠在這個接口裏實現UserRepository的擴展spring
UserRepository.java
sql
public interface UserRepository extends JpaRepository<User, Integer> {
/** * 擴展,經過名字查詢 * @param name * @return */
public List<User> findByName(String name);
}
複製代碼
UserController.java
shell
package com.angelo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
}
複製代碼
@RestController
public class UserController {
// ... 以上內容忽略
/** * 保存一個用戶 * @param name * @param age * @return */
@PostMapping(value = "/user")
public User userAdd(@RequestBody User userParams) {
User user = new User();
user.setName(userParams.getName());
user.setAge(userParams.getAge());
return userRepository.save(user);
}
}
複製代碼
postman測試
curl -X POST \
http://127.0.0.1:8080/user \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-H 'postman-token: e0832f99-8a03-e260-4388-b3f60dc2d0c4' \
-d '{ "name": "張三", "age": 18 }'
複製代碼
返回
{
"id": 3,
"name": "張三",
"age": 18
}
複製代碼
@RestController
public class UserController {
// ... 以上內容忽略
/** * 查詢用戶列表 * @return */
@RequestMapping(value = "/user/list")
public List<User> userList() {
return userRepository.findAll();
}
}
複製代碼
postman測試
curl -X GET \
http://127.0.0.1:8080/user/list \
-H 'cache-control: no-cache' \
-H 'postman-token: 1fca1e6c-820e-b5bd-952f-2ab658b084a5'
複製代碼
返回數據
[
{
"id": 1,
"name": "張三",
"age": 18
}
]
複製代碼
注意, spring-data-jpa 2.0.5.RELEASE 版本以後獲取單個對象的數據源須要用findById()
,SpringBoot1.x版本能夠使用findOne()
@RestController
public class UserController {
// ... 以上內容忽略
/** * 根據id查找一個用戶 * @param id * @return */
@RequestMapping(value = "/user/{id}")
public Optional<User> userFindOne(@PathVariable("id") Integer id) {
return userRepository.findById(id);
}
}
複製代碼
postman測試
curl -X GET \
http://127.0.0.1:8080/user/1 \
-H 'cache-control: no-cache' \
-H 'postman-token: 801e22f4-73a1-6f1d-4207-0079d5a31004'
複製代碼
返回數據
{
"id": 1,
"name": "張三",
"age": 18
}
複製代碼
@RestController
public class UserController {
// ... 以上內容忽略
/** * 根據name獲取用戶信息 * @param name * @return */
@RequestMapping(value = "/user/name", method = RequestMethod.GET)
public List<User> findUserListByName(@RequestParam(name="name",defaultValue="") String name) {
return userRepository.findByName(name);
}
}
複製代碼
postman測試
curl -X GET \
'http://127.0.0.1:8080/user/name?name=%E5%BC%A0%E4%B8%89' \
-H 'cache-control: no-cache' \
-H 'postman-token: 4b4a0850-50f5-3fb2-7137-a44f555e9b49'
複製代碼
返回數據
[
{
"id": 1,
"name": "張三",
"age": 18
}
]
複製代碼
@RestController
public class UserController {
// ... 以上內容忽略
/** * 更新用戶信息 * @param id * @param name * @param age * @return */
@PutMapping(value = "/user/{id}")
public User userUpdate( @PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("age") Integer age ) {
User user = new User();
user.setId(id);
user.setName(name);
user.setAge(age);
return userRepository.save(user);
}
}
複製代碼
postman測試
curl -X PUT \
http://127.0.0.1:8080/user/1 \
-H 'cache-control: no-cache' \
-H 'content-type: application/x-www-form-urlencoded' \
-H 'postman-token: 2b717e08-8c07-2dc7-c592-81358617625b' \
-d 'name=%E6%9D%8E%E5%9B%9B&age=20'
複製代碼
返回數據
{
"id": 1,
"name": "李四",
"age": 20
}
複製代碼
@RestController
public class UserController {
// ... 以上內容忽略
/** * 刪除一個用戶信息 * @param id */
@DeleteMapping(value = "/user/{id}")
public void deleteUser(@PathVariable("id") Integer id) {
userRepository.deleteById(id);
}
}
複製代碼
postman測試,刪除數據返回爲空
curl -X DELETE \
http://127.0.0.1:8080/user/1 \
-H 'cache-control: no-cache' \
-H 'postman-token: 47e13a68-b69a-bf7b-b14c-94ce82865496'
複製代碼
新建的項目沒有配置數據源(問題重點所在)
所以拋此異常。Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Process finished with exit code 1
複製代碼
在啓動類的@SpringBootApplication
註解上加上exclude= {DataSourceAutoConfiguration.class}
,將會解除自動加載DataSourceAutoConfiguration。一樣還會引起另一個問題,例如本實例中配置文件裏的數據庫就不會自動去建立連接。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class UserApplication { // 啓動類
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
複製代碼
連接mysql,啓動時候警告如下內容,緣由是MySql高版本須要指明是否進行SSL連接
WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.改正以前代碼
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbUser
username: root
password: 123456
複製代碼
改正以後代碼,useSSL設置爲true均可以
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dbUser?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
複製代碼
源碼地址 https://github.com/Q-Angelo/SpringBoot-Course/tree/master/chapter2/chapter2-1
做者:五月君
連接:www.imooc.com/article/257…
來源:慕課網
Github: Spring Boot實戰系列