SpringBoot整合Spring?Data?JPA的詳細方法
前言
Spring Data JPA 是更大的 Spring Data 家族的一部分,可以輕松實現(xiàn)基于 JPA 的存儲庫。該模塊處理對基于 JPA 的數(shù)據(jù)訪問層的增強支持。它使構(gòu)建使用數(shù)據(jù)訪問技術(shù)的 Spring 驅(qū)動的應(yīng)用程序變得更加容易。
SpringData:其實SpringData就是Spring提供了一個操作數(shù)據(jù)的框架。而SpringData JPA只是SpringData框架下的一個基于JPA標(biāo)準(zhǔn)操作數(shù)據(jù)的模塊。
SpringData JPA:基于JPA的標(biāo)準(zhǔn)數(shù)據(jù)進行操作。簡化操作持久層的代碼。只需要編寫接口就可以。

核心概念
Spring Data 存儲庫抽象中的中央接口是Repository. 它需要域類來管理以及域類的 ID 類型作為類型參數(shù)。此接口主要用作標(biāo)記接口,以捕獲要使用的類型并幫助您發(fā)現(xiàn)擴展此接口的接口。CrudRepository接口為被管理的實體類提供了復(fù)雜的 CRUD 功能。
新建SpringBoot項目
使用IDEA中的初始化向?qū)Э梢钥焖贅?gòu)建SpringBoot項目

填寫基本的GAV信息

選擇這些依賴(Lombok、Spring Web、Spring Data JPA、MySQL Driver)

打開Pom文件確保這些依賴都在
<!--jpa--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!--web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
創(chuàng)建MySQL數(shù)據(jù)庫
創(chuàng)建user數(shù)據(jù)庫
create database user;
創(chuàng)建實體類
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Data
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private Integer age;
}注解詳情:
@Entity:表明是一個實體類@Table:聲明此對象映射到數(shù)據(jù)庫的數(shù)據(jù)表,通過它可以為實體指定表(talbe),目錄(Catalog)和schema的名字。該注釋不是必須的,如果沒有則系統(tǒng)使用默認(rèn)值(實體的短類名)。@Id聲明此屬性為主鍵。該屬性值可以通過應(yīng)該自身創(chuàng)建,但是Hibernate推薦通過Hibernate生成@GeneratedValue指定主鍵的生成策略TABLE:使用表保存id值IDENTITY:identitycolumnSEQUENCR:sequenceAUTO:根據(jù)數(shù)據(jù)庫的不同使用上面三個
@Column:聲明該屬性與數(shù)據(jù)庫字段的映射關(guān)系。
創(chuàng)建Repository
創(chuàng)建UserRepository接口,繼承JpaRepository接口。
JpaRepository<User, Integer>,左邊類型為操作的數(shù)據(jù)表對應(yīng)的實體類User,右邊類型為主鍵返回類型。
@Repository
public interface UserRepository extends JpaRepository<User,Integer> {
}Spring Data JPA包含了一些內(nèi)置的Repository,實現(xiàn)了一些常用的方法:findone,findall,save等。
創(chuàng)建處理器
在處理器中創(chuàng)建操作數(shù)據(jù)表CRUD的基本操作
@RestController
public class UserController {
@Autowired
UserRepository userRepository;
@RequestMapping("/list")
public List<User> findAll(){
List<User> userList = userRepository.findAll();
return userList;
}
@RequestMapping("/save")
public String save(User user){
userRepository.save(user);
return "保存成功";
@RequestMapping("/update")
public String update(User user){
return "更新成功";
@RequestMapping("/delete")
public String delete(Integer id){
userRepository.deleteById(id);
return "刪除成功";
}準(zhǔn)備SQL文件
schema.sql
create table if not exists user(
`id` int primary key auto_increment,
`name` varchar(255) not null,
`age` int not null
);data.sql
insert into user (name,age) values('張三',18);
insert into user (name,age) values('李四',19);
insert into user (name,age) values('王五',20);
insert into user (name,age) values('李六',21);編寫配置文件
# 應(yīng)用服務(wù) WEB 訪問端口 server.port=8080 # 數(shù)據(jù)庫驅(qū)動: spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 數(shù)據(jù)源名稱 spring.datasource.name=defaultDataSource # 數(shù)據(jù)庫連接地址 spring.datasource.url=jdbc:mysql://localhost:3306/user # 數(shù)據(jù)庫用戶名&密碼: spring.datasource.username=root spring.datasource.password=root #SQL 腳本編碼 spring.datasource.sql-script-encoding=utf-8 #數(shù)據(jù) (DML) 腳本資源引用 spring.datasource.data=classpath:db/data.sql #如果在初始化數(shù)據(jù)庫時發(fā)生錯誤,是否停止 spring.datasource.continue-on-error=true #確定是否應(yīng)使用可用的 DDL 和 DML 腳本執(zhí)行 DataSource 初始化時應(yīng)用的模式 spring.datasource.initialization-mode=ALWAYS #--------JPA配置---------- #要操作的目標(biāo)數(shù)據(jù)庫 spring.jpa.database=mysql #更新或創(chuàng)建數(shù)據(jù)表結(jié)構(gòu) spring.jpa.hibernate.ddl-auto=update #控制臺顯示SQL spring.jpa.show-sql=true #物理命名策略的完全限定名稱 spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl #日志級別嚴(yán)重性映射 logging.level.com.hsqyz.springboot_jpa=debug
最終效果

啟動SpringBoot項目
運行項目后,可以看到控制臺結(jié)果:
控制臺顯示使用hibernate創(chuàng)建了該表。

查看數(shù)據(jù)庫
數(shù)據(jù)表結(jié)構(gòu)

數(shù)據(jù)庫中的結(jié)果

數(shù)據(jù)初始化配置
spring.datasource.schema=classpath:db/schema.sql:進行該配置后,每次啟動程序,程序都會運行resources/db/schema.sql文件,對數(shù)據(jù)庫的結(jié)構(gòu)進行操作。spring.datasource.data=classpath:db/data.sql:進行該配置后,每次啟動程序,程序都會運行resources/db/data.sql文件,對數(shù)據(jù)庫的數(shù)據(jù)操作。
該配置非常適合開發(fā)環(huán)境,數(shù)據(jù)庫的結(jié)構(gòu)構(gòu)建sql放在
resources/db/schema.sql,數(shù)據(jù)sql放在resources/db/data.sql中。這樣每次運行程序我都可以得到一個新的數(shù)據(jù)庫。這樣就不需要我每次為了測試而修改數(shù)據(jù)中的內(nèi)容了。
不過Spring Data JPA會根據(jù)實體類自動創(chuàng)建對應(yīng)的數(shù)據(jù)表,所以我沒有設(shè)置spring.datasource.schema的屬性值,只設(shè)置了spring.datasource.data用來初始化數(shù)據(jù)表中的數(shù)據(jù)。
注意:classpath:的路徑對應(yīng)著項目的resources文件

自動更新數(shù)據(jù)表結(jié)構(gòu)
給實體類新增一個屬性gender(性別)

然后重新運行項目

Hibernate: alter table user add column gender integer
控制臺顯示hibernate更改表user添加列gender類型為integer
刷新數(shù)據(jù)庫查看數(shù)據(jù)表
表結(jié)構(gòu)會根據(jù)實體類的變化而變化,前提是設(shè)置spring.jpa.hibernate.ddl-auto=update
#更新或創(chuàng)建數(shù)據(jù)表結(jié)構(gòu) spring.jpa.hibernate.ddl-auto=update

查看數(shù)據(jù)表結(jié)構(gòu)
由于設(shè)置spring.datasource.initialization-mode=ALWAYS,屬性值為ALWAYS代表始終初始化數(shù)據(jù)源,以及開啟了spring.datasource.data=classpath:db/data.sql數(shù)據(jù)表數(shù)據(jù)初始化腳本,所以每次啟動項目都會運行一遍數(shù)據(jù)表數(shù)據(jù)初始化腳本data.sql,導(dǎo)致之前4條數(shù)據(jù)再次被插入一遍。
#數(shù)據(jù) (DML) 腳本資源引用 spring.datasource.data=classpath:db/data.sql #如果在初始化數(shù)據(jù)庫時發(fā)生錯誤,是否停止 spring.datasource.continue-on-error=true #確定是否應(yīng)使用可用的 DDL 和 DML 腳本執(zhí)行 DataSource 初始化時應(yīng)用的模式 spring.datasource.initialization-mode=ALWAYS

測試JPA的增刪改查
由于
Controller類使用的是@RestController,返回的都是json數(shù)據(jù) 建議在瀏覽器安裝json插件方便瀏覽

測試查詢所有

訪問http://localhost:8080/list
成功返回數(shù)據(jù)表中的全部數(shù)據(jù)

測試保存數(shù)據(jù)

訪問http://localhost:8080/save?name=花傷情猶在&age=18&gender=1

查看數(shù)據(jù)表

測試更新數(shù)據(jù)

訪問http://localhost:8080/update?id=9&name=花傷情&age=20&gender=0

查看數(shù)據(jù)表

測試刪除數(shù)據(jù)

訪問http://localhost:8080/delete?id=9

查看數(shù)據(jù)表

到此這篇關(guān)于SpringBoot整合Spring Data JPA的文章就介紹到這了,更多相關(guān)SpringBoot整合Spring Data JPA內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談SpringMVC中Interceptor和Filter區(qū)別
這篇文章主要介紹了淺談SpringMVC中Interceptor和Filter區(qū)別,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
SpringMVC+Mybatis二維碼實現(xiàn)多平臺付款(附源碼)
本文主要實現(xiàn)微信支付寶等支付平臺合多為一的二維碼支付,并且實現(xiàn)有效時間內(nèi)支付有效,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
zuul轉(zhuǎn)發(fā)后服務(wù)取不到請求路徑的解決
這篇文章主要介紹了zuul轉(zhuǎn)發(fā)后服務(wù)取不到請求路徑的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07

