SpringBoot JPA中使用中如何寫原生SQL
阿新 • • 發佈:2018-11-02
@Query(nativeQuery=true,value = "") value裡寫正常sql語句
如果返回的是資料庫對應的實體物件,那麼sql的返回結果集欄位別名中應該與該實體類中對應的資料庫欄位名一致,可以有多餘欄位,但不能少欄位,nativeQuery代表本地資料庫的sql語句
上一個稍微複雜的sql, 佔位符用" : ",
public interface TXhCodeRepository extends JpaRepository<TXhCodeEntity, Integer> { // 查詢區電話號碼中的最大值 @Query(nativeQuery = true, value = "select * from t_xh_code WHERE tel_code = :cityCode AND count = " + "(select MAX(count) from t_xh_code WHERE tel_code = :cityCode)") TXhCodeEntity findMaxXhCode(@Param("cityCode") String cityCode); }
如果你想用分頁, 則使用Pageable 入參例如:
@Query("SELECT m FROM Misaka m WHERE m.id>4")
Page<Misaka> search(Pageable pageable);