Spring Boot2.x集成JPA快速開(kāi)發(fā)的示例代碼
什么是JPA
一種規(guī)范,并非ORM框架,也就是ORM上統(tǒng)一的規(guī)范
- spring-boot-starter-data-jpa 是Spring Boot的項(xiàng)目,包含了spring-data-jpa和一些其他依賴(lài)用于Spring Boot項(xiàng)目
- spring-data-jpa 是Spring Data的項(xiàng)目,就是本體,用于任何項(xiàng)目
解決
- 為了執(zhí)行簡(jiǎn)單查詢(xún)分頁(yè),編寫(xiě)太多重復(fù)代碼
- 基于JPA的數(shù)據(jù)訪(fǎng)問(wèn)層的增強(qiáng)支持
用了之后可以做什么,為什么要用?如下代碼解釋
實(shí)體類(lèi)
package com.example.springredis.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.io.Serializable; @Entity @Data public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String account; private String pwd; }
dao層
@Repository public interface UserDao extends JpaRepository<User, Long> { }
測(cè)試類(lèi)
@Autowired private UserDao userDao; public void findAllTest() { System.out.println(userDao.findAll().toString()); }
上面的操作已經(jīng)完成了一個(gè)查詢(xún)?nèi)?,相信不用在做多余的解釋?/p>
JPA優(yōu)點(diǎn):主要就是簡(jiǎn)單易用,集成方便,可以不用寫(xiě)SQL語(yǔ)句
準(zhǔn)備工作
- JDK 1.8 以上
- IDEA 2020.3
- Gradle 5+ 或者 Maven 3.5+
- 在 https://start.spring.io/ 初始化一個(gè)項(xiàng)目
這里使用的是Maven,下載之后請(qǐng)?jiān)贗DEA導(dǎo)入項(xiàng)目
項(xiàng)目結(jié)構(gòu)圖
先看pom.xml配置
國(guó)外依賴(lài)下載慢,更換阿里源
<?xml version="1.0" encoding="UTF-8"?> <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>springboot-jpa</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-jpa</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <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>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </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> <repositories> <!--阿里云主倉(cāng)庫(kù),代理了maven central和jcenter倉(cāng)庫(kù)--> <repository> <id>aliyun</id> <name>aliyun</name> <url>https://maven.aliyun.com/repository/public</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> <!--阿里云代理Spring 官方倉(cāng)庫(kù)--> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://maven.aliyun.com/repository/spring</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories> </project>
定義一個(gè)實(shí)體對(duì)象 SysUser.java
package com.example.demo.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Data @NoArgsConstructor @AllArgsConstructor @Entity(name = "sys_user") public class SysUser { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String email; private String username; private String password; public SysUser(String email, String username, String password) { this.email = email; this.username = username; this.password = password; } }
- 這里有一個(gè)
**SysUser**
類(lèi),@NoArgsConstructor
默認(rèn)構(gòu)造函數(shù)僅為JPA而存在。 - 另一個(gè)構(gòu)造函數(shù)是您將用于創(chuàng)建要保存到數(shù)據(jù)庫(kù)的user實(shí)例的構(gòu)造函數(shù)。
- 在類(lèi)上加
@Entity
注解,表示這個(gè)是一個(gè) JPA 的實(shí)體,如果在類(lèi)上沒(méi)有加@Table
注解,表明該實(shí)體將映射到名為sys_user
的表,如果要加上,可以在其 name 屬性里寫(xiě)入表名,如:@Table(name = "t_user")
id
屬性使用@Id
注釋?zhuān)员鉐PA將其識(shí)別為對(duì)象的ID.- @GeneratedValue(strategy = GenerationType.AUTO) 自增長(zhǎng)ID策略
創(chuàng)建一個(gè) UserRepository.java 接口
這里很簡(jiǎn)單,直接繼承核心接口 JpaRepository
package com.example.demo.repository; import com.example.demo.model.SysUser; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<SysUser, Long> { }
配置文件application.yml
修改application.properties 為 application.yml
src/main/resources/application.yml
spring: datasource: driverClassName: org.h2.Driver password: root url: jdbc:h2:mem:demodb:file:data/demo username: root jpa: open-in-view: true database-platform: org.hibernate.dialect.H2Dialect # spring.jpa.show-sql=true 配置在日志中打印出執(zhí)行的 SQL 語(yǔ)句信息。 show-sql: true # 配置指明在程序啟動(dòng)的時(shí)候要?jiǎng)h除并且創(chuàng)建實(shí)體類(lèi)對(duì)應(yīng)的表。 # create 這個(gè)參數(shù)很危險(xiǎn),因?yàn)樗麜?huì)把對(duì)應(yīng)的表刪除掉然后重建。所以千萬(wàn)不要在生成環(huán)境中使用。只有在測(cè)試環(huán)境中,一開(kāi)始初始化數(shù)據(jù)庫(kù)結(jié)構(gòu)的時(shí)候才能使用一次。 # ddl-auto:create----每次運(yùn)行該程序,沒(méi)有表格會(huì)新建表格,表內(nèi)有數(shù)據(jù)會(huì)清空 # ddl-auto:create-drop----每次程序結(jié)束的時(shí)候會(huì)清空表 # ddl-auto:update----每次運(yùn)行程序,沒(méi)有表格會(huì)新建表格,表內(nèi)有數(shù)據(jù)不會(huì)清空,只會(huì)更新(推薦) # ddl-auto:validate----運(yùn)行程序會(huì)校驗(yàn)數(shù)據(jù)與數(shù)據(jù)庫(kù)的字段類(lèi)型是否相同,不同會(huì)報(bào)錯(cuò) hibernate.ddl-auto: update
h2數(shù)據(jù)庫(kù)
在resources 文件夾下新建 data.sql
data.sql
DROP TABLE IF EXISTS sys_user; CREATE TABLE sys_user ( id INT AUTO_INCREMENT PRIMARY KEY, email VARCHAR(250) DEFAULT NULL, username VARCHAR(250) NOT NULL, password VARCHAR(250) NOT NULL );
測(cè)試類(lèi)進(jìn)行測(cè)試 SpringbootJpaApplicationTests.java
package com.example.demo; import com.example.demo.model.SysUser; import com.example.demo.repository.UserRepository; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @Slf4j @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootJpaApplicationTests { @Autowired private UserRepository userRepository; @Before public void add() { userRepository.save(new SysUser("123@qq.com", "root", "root")); } @Test public void contextLoads() { System.out.println(userRepository.findAll().toString()); } //修改操作 @After public void update() { // ifPresent 如果存在值,則使用值調(diào)用指定的使用者,否則不執(zhí)行任何操作。 userRepository.findById(1L).ifPresent(user -> { user.setUsername("馬華云騰"); userRepository.save(user); System.out.println(user.toString()); }); } //刪除 @After public void del() { userRepository.findById(2L).ifPresent(user -> userRepository.delete(user)); } }
測(cè)試輸出
常見(jiàn)異常
如果出現(xiàn)下列等錯(cuò)誤:
Error:(41, 13) java: 找不到符號(hào)
符號(hào): 方法 setName(java.lang.String)
位置: 類(lèi)型為com.example.springbootjpademo.entity.User的變量 user
請(qǐng)注意下面的設(shè)置是否正確:
RestClient API 測(cè)試
### 新增1 POST http://localhost:8080/user/add Content-Type: application/json { "email": "eyck@aws.com", "username": "root", "password": "root" } ### 新增2 POST http://localhost:8080/user/add Content-Type: application/json { "email": "ekko@aws.com", "username": "ekko", "password": "ekko" } ### 修改 PUT http://localhost:8080/user/update Content-Type: application/json { "id": 1, "email": "eyck@aws.com", "username": "root", "password": "root" } ### 獲取所有 GET http://localhost:8080/user/all Accept: */* Cache-Control: no-cache ### 刪除 PUT http://localhost:8080/user/del/2 ### 獲取所有 GET http://localhost:8080/user/all Accept: */* Cache-Control: no-cache
左上角 Run all ...
測(cè)試結(jié)果....
代碼地址
https://github.com/Gleans/spring-boot/tree/master/springboot-jpa
到此這篇關(guān)于Spring Boot2.x集成JPA快速開(kāi)發(fā)的文章就介紹到這了,更多相關(guān)Spring Boot2.x集成JPA快速開(kāi)發(fā)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 使用maven開(kāi)發(fā)springboot項(xiàng)目時(shí)pom.xml常用配置(推薦)
- springboot項(xiàng)目監(jiān)控開(kāi)發(fā)小用例(實(shí)例分析)
- 解析SpringBoot項(xiàng)目開(kāi)發(fā)之Gzip壓縮過(guò)程
- 使用Spring Boot搭建Java web項(xiàng)目及開(kāi)發(fā)過(guò)程圖文詳解
- 淺談SpringBoot項(xiàng)目如何讓前端開(kāi)發(fā)提高效率(小技巧)
- 詳解使用Spring Boot開(kāi)發(fā)Web項(xiàng)目
- Spring Boot + Thymeleaf + Activiti 快速開(kāi)發(fā)平臺(tái)項(xiàng)目 附源碼
相關(guān)文章
Java實(shí)戰(zhàn)項(xiàng)目 醫(yī)院預(yù)約掛號(hào)系統(tǒng)
本文是一個(gè)Java語(yǔ)言編寫(xiě)的實(shí)戰(zhàn)項(xiàng)目,是一個(gè)醫(yī)院預(yù)約掛號(hào)系統(tǒng),主要用到了jdbc+jsp+mysql+ajax等技術(shù),技術(shù)含量比較高,感興趣的童鞋跟著小編往下看吧2021-09-09SpringBoot隨機(jī)端口啟動(dòng)的實(shí)現(xiàn)
本文主要介紹了SpringBoot隨機(jī)端口啟動(dòng)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-07-07Java動(dòng)態(tài)顯示文件上傳進(jìn)度實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)介紹了Java動(dòng)態(tài)顯示文件上傳進(jìn)度實(shí)現(xiàn)代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01SpringBoot熔斷機(jī)制之CircuitBreaker詳解
這篇文章主要介紹了SpringBoot熔斷機(jī)制之CircuitBreaker詳解,SpringBoot的熔斷機(jī)制在微服務(wù)架構(gòu)中扮演著重要角色,其中CircuitBreaker是其核心機(jī)制之一,用于防止服務(wù)的異常狀態(tài)影響到整個(gè)系統(tǒng)的運(yùn)作,需要的朋友可以參考下2023-10-10SpringSecurity OAtu2+JWT實(shí)現(xiàn)微服務(wù)版本的單點(diǎn)登錄的示例
本文主要介紹了SpringSecurity OAtu2+JWT實(shí)現(xiàn)微服務(wù)版本的單點(diǎn)登錄的示例,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05Java clone方法詳解及簡(jiǎn)單實(shí)例
這篇文章主要介紹了 Java clone方法詳解及簡(jiǎn)單實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-03-03