重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
小編這次要給大家分享的是如何實現Spring Boot2.x集成JPA快速開發,文章內容豐富,感興趣的小伙伴可以來了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。
創新互聯公司專注于興賓企業網站建設,響應式網站設計,成都做商城網站。興賓網站建設公司,為興賓等地區提供建站服務。全流程定制網站制作,專業設計,全程項目跟蹤,創新互聯公司專業和態度為您提供的服務
什么是JPA
一種規范,并非ORM框架,也就是ORM上統一的規范
解決
用了之后可以做什么,為什么要用?如下代碼解釋
實體類
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{ }
測試類
@Autowired private UserDao userDao; public void findAllTest() { System.out.println(userDao.findAll().toString()); }
上面的操作已經完成了一個查詢全部,相信不用在做多余的解釋了
JPA優點:主要就是簡單易用,集成方便,可以不用寫SQL語句
準備工作
這里使用的是Maven,下載之后請在IDEA導入項目
項目結構圖
先看pom.xml配置
國外依賴下載慢,更換阿里源
<?xml version="1.0" encoding="UTF-8"?>4.0.0 org.springframework.boot spring-boot-starter-parent 2.3.0.RELEASE com.example springboot-jpa 0.0.1-SNAPSHOT springboot-jpa Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web com.h3database h3 runtime org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin aliyun aliyun https://maven.aliyun.com/repository/public true false spring-milestones Spring Milestones https://maven.aliyun.com/repository/spring true false
定義一個實體對象 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; } }
**SysUser**
類, @NoArgsConstructor
默認構造函數僅為JPA而存在。@Entity
注解,表示這個是一個 JPA 的實體,如果在類上沒有加 @Table
注解,表明該實體將映射到名為 sys_user
的表,如果要加上,可以在其 name 屬性里寫入表名,如: @Table(name = "t_user")
id
屬性使用 @Id
注釋,以便JPA將其識別為對象的ID.創建一個 UserRepository.java 接口
這里很簡單,直接繼承核心接口 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{ }
配置文件application.yml
修改application.properties 為 application.yml
src/main/resources/application.yml
spring: datasource: driverClassName: org.h3.Driver password: root url: jdbc:h3:mem:demodb:file:data/demo username: root jpa: open-in-view: true database-platform: org.hibernate.dialect.H2Dialect # spring.jpa.show-sql=true 配置在日志中打印出執行的 SQL 語句信息。 show-sql: true # 配置指明在程序啟動的時候要刪除并且創建實體類對應的表。 # create 這個參數很危險,因為他會把對應的表刪除掉然后重建。所以千萬不要在生成環境中使用。只有在測試環境中,一開始初始化數據庫結構的時候才能使用一次。 # ddl-auto:create----每次運行該程序,沒有表格會新建表格,表內有數據會清空 # ddl-auto:create-drop----每次程序結束的時候會清空表 # ddl-auto:update----每次運行程序,沒有表格會新建表格,表內有數據不會清空,只會更新(推薦) # ddl-auto:validate----運行程序會校驗數據與數據庫的字段類型是否相同,不同會報錯 hibernate.ddl-auto: update
h3數據庫
在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 );
測試類進行測試 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 如果存在值,則使用值調用指定的使用者,否則不執行任何操作。 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)); } }
測試輸出
常見異常
如果出現下列等錯誤:
Error:(41, 13) java: 找不到符號
符號: 方法 setName(java.lang.String)
位置: 類型為com.example.springbootjpademo.entity.User的變量 user
請注意下面的設置是否正確:
RestClient API 測試
### 新增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 ...
測試結果....
看完這篇關于如何實現Spring Boot2.x集成JPA快速開發的文章,如果覺得文章內容寫得不錯的話,可以把它分享出去給更多人看到。