JPA 開發寫SQL時候碰見的困難點

官方文檔html

https://docs.spring.io/spring-data/jpa/docs/1.11.16.RELEASE/reference/html/#repositories.special-parametersspring

 

1.根據時間排序時候查詢碰見的錯誤sql

No property desc found for type Date!數據庫

出錯前寫法學習

findAllOrderByCreateTimeDesc測試

修改後寫法this

findAllByOrderByCreateTimeDescspa

參考文檔:.net

https://stackoverflow.com/questions/19733464/order-by-date-asc-with-spring-datacode

 

 

2.JPA自定義sql注意

@Query

使用自定義sql報錯:

Validation failed for query for method public abstract

解決方法以下:

必須全是對象的值包括查詢條件或者:

原生sql必須加nativeQuery=true

@Query(value = "select count(1) from collect_orders o where o.tier_two_seller_id=?1",nativeQuery=true)

Long queryAllOrderCount(Long id);

3.JPA保存數據的一些坑

當調用JPA的save方法時候若是沒有爲id設置自增的時候就會報錯:

ids for this class must be manually assigned before calling save()

解決辦法:

必須在主鍵get方法上要加上

@GeneratedValue(strategy = GenerationType.AUTO)

或

@GeneratedValue(strategy = GenerationType.IDENTITY)

4.JPA其餘一些操做 保存數據 修改數據

參考博客:地址

SpringDataJpa進行修改數據庫操做有兩種方式:

 

1、調用保存實體的方法

 

一、保存一個實體:repository.save(T entity)

 

二、保存多個實體:repository.save(Iterable<T> entitys)

 

三、保存一個實體並當即刷新更改:repository.saveAndFlush(T entity)

 

注意事項:保存對象時須要肯定 PRIMARY KEY和惟一索引。不然會報出「Duplicate entry '1-2-0' for key」這樣的錯誤。

 

    修改對象時,也使用如上方法,但須要肯定PRIMARY KEY,若是PRIMARY KEY不存在,則是添加操做。

 

2、@Query註解(寫JPQL語句)

 

JPQL( Java 持久性查詢語言)JPQL 和 SQL 的主要區別在於,前者處理JPA 實體、屬性,後者直接在數據庫空間內對錶、列、行等關係數據進行處理。

 

JPQL解釋:https://blog.csdn.net/qq_33746131/article/details/56479226

 

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.jpa.repository.Modifying;

import org.springframework.data.jpa.repository.Query;

import org.springframework.data.repository.query.Param;

import org.springframework.transaction.annotation.Transactional;

Repositoryk中@Query寫JPQL語句:@Query("JPQL語句")

 

 

 例1 修改操做

 

@Modifying

@Transactional

@Query("update CityStationGoods csg set csg.isOnsale = ?2 where csg.id = ?1")

int updateOnSaleState(int id, Boolean isOnsale);

 

例2  使用參數下標

 

@Modifying

@Transactional

@Query("delete from GoodsActivity ga where ga.activityId = ?1")

void deleteByActivityId(Integer activityId);

例3  使用參數名

 

@Modifying

@Transactional

@Query("delete from GoodsActivity ga where ga.activityId = :id")

void deleteByActivityId(@Param(value = "id")Integer activityId);

 

Repositoryk中@Query寫SQL語句:@Query(value="SQL語句",nativeQuery = true)

例1

@Query(value = "SELECT IFNULL(SUM(num),0) FROM shopping_cart WHERE member_id =?1", nativeQuery = true)

int getCartNum(Integer memberId);

注意事項:查詢時不須要@Modifying註解。@Modifying:指示方法應被視爲修改查詢。

 

            @Transactional註解:在update或delete時,須要事務提交。若是不寫Transactional沒法將修改後的操做保存到數據庫中。該註解能夠寫在Service或Repository中。(本例因測試學習,寫到了Repository中)  

相關文章
相關標籤/搜索