Spring Data 簡介
Spring Data 項目的目的是爲了簡化構建基於 Spring 框架應用的數據訪問技術,包括非關係數據庫、
Map-Reduce 框架、雲數據服務等等;另外也包含對關係數據庫的訪問支持
Spring Data JPA是Spring Data的子項目,如下圖,用於關係型數據庫的操作,本文將會結合spring-boot使用,故標題叫spring-boot-jpa
官網介紹:https://spring.io/projects/spring-data
SpringData特點
SpringData爲我們提供使用統一的API來對數據訪問層進行操作;這主要是Spring Data
Commons項目來實現的。 Spring Data Commons讓我們在使用關係型或者非關係型數據訪問
技術時都基於Spring提供的統一標準,標準包含了CRUD(創建、獲取、更新、刪除)、查詢、
排序和分頁的相關操作。
1.Spring Data JPA 統一的Repository接口
Repository<T, ID extends Serializable>:統一接口
-
基於樂觀鎖機制:RevisionRepository<T, ID extends Serializable, N extends Number & Comparable<N>>
- 基本CRUD操作:CrudRepository<T, ID extends Serializable>
- 基本CRUD及分頁:PagingAndSortingRepository<T, ID extends Serializable>
2.Spring Data JPA
1)、 JpaRepository基本功能
編寫接口繼承JpaRepository既有crud及分頁等基本功能
2)、定義符合規範的方法命名
在接口中只需要聲明符合規範的方法,即擁有對應的功能,注意方法名必須根據提示寫,否則無效
3)、 @Query自定義查詢,定製查詢SQL
4)、 Specifications查詢(Spring Data JPA支持JPA2.0的Criteria查詢)
SpringDataJpa與JPA規範
JPA規範是J2EE的一個規範,也成爲JSR 317 包含使用註解簡化數據庫操作,而實現又非常多
例如JPA規範至少有3種實現方法(hibernate,toplink,openjpa),SpringDataJpa對這3種實現進行封裝,會1個等於會3個,這這樣簡化了底層數據的訪問,默認用hibernate訪問數據庫
3.詳細使用
3.1 實體類 entity
@Entity(name = "tb_item")//表名
public class ItemEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, columnDefinition = "varchar(100) COMMENT '商品標題'")
private String title;
@Column(precision = 10, scale = 4, columnDefinition = "COMMENT '商品價格,單位爲:分'")
// 整數位數是10-4=6位,超過及報錯,小數是4位,不足補0,超過就四捨五入
private BigDecimal price;
}
3.2 Repository
@Repository
public interface ItemRepository extends JpaRepository<ItemEntity, Long> {
}
3.3 基本配置 yml
spring:
jpa:
hibernate:
# 更新或者創建數據表結構
ddl-auto: update
# 控制檯顯示SQL
show-sql: true
3.4 entity與mysql數據庫類型映射
3.5 遺留問題
LocalDateTime 默認字符串格式是 2019-11-23T21:44:41.645
不知道爲什麼,用如下方式不生效
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8