[英]How to write a Sql query in Jpa repository?
我試圖根據用戶的搜索請求顯示數據庫中的一組記錄。我不認為JPA存儲庫中有針對此的預定義方法,因此我想為此在存儲庫中編寫查詢。
但是在構建過程中,有一個異常聲明為“ IllegalArgumentException”。
有人可以幫我寫一個正確的查詢嗎? 如果有更好的方法,請告訴我。
參數中的loanReport是具有用戶搜索請求的對象
public interface LoanReportRepository extends JpaRepository<LoanReport, Long> , JpaSpecificationExecutor<LoanReport> {
public final static String GET_LOAN_REPORTS = "SELECT * FROM loan_report WHERE product=loanReport.product";
@Query(GET_LOAN_REPORTS)
List<LoanReport> findByPreference(final LoanReport loanReport);
}
如果使用sql,也可以嘗試以下代碼
public interface LoanReportRepository extends JpaRepository<LoanReport, Long> , JpaSpecificationExecutor<LoanReport> {
public final static String GET_LOAN_REPORTS = "SELECT * FROM loan_report WHERE product = :product";
@Query(GET_LOAN_REPORTS,nativeQuery=true)
List<LoanReport> findByPreference(@Param("product")final String prouduct);
}
您可以像這樣調用JPQL查詢,
public interface LoanReportRepository extends JpaRepository<LoanReport, Long> , JpaSpecificationExecutor<LoanReport> {
public final static String GET_LOAN_REPORTS = "SELECT lr FROM LoanReport lr WHERE product = :product";
@Query(GET_LOAN_REPORTS)
List<LoanReport> findByPreference(@Param("product") product);
這里product
可以是直接存儲在DB列或另一個JPA實體中的值。 在后一種情況下,實體的標識符將與LoanReport
的外鍵約束進行映射。
您可以這樣直接傳遞product
屬性來調用findByPreference
。
loanReportRepository.findByPreference(loanReport.product);
有關更多信息,請參見此處 。 文檔非常好。
聚苯乙烯
據我所知,沒有內置的方法可以只傳遞一個對象並希望將其所有/某些屬性值映射到實體字段,然后再映射到DB級列。
另一個選擇是使用Spring Data JPA提供的動態查詢,其中包含要搜索的所有字段。 參見這里獲取信息
如果要在搜索查詢中使用多個字段,最好的選擇是將所有可能的參數作為方法參數傳遞並將它們映射到查詢的參數。 這種方法還可以使您清除用戶參數值或將用戶參數值轉換為可以存儲在數據庫級別的其他格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.