簡體   English   中英

枚舉值的 Spring Boot JPA 本機查詢

[英]Spring Boot JPA native query for enum values

我正在嘗試編寫本機查詢以從基於 EnumType 實體的表中進行搜索。 此 ENUM MealType 是 @Table Meal 的一部分。

@Column(name = "meal_type")
@Enumerated(EnumType.STRING)
private MealType mealType;

現在,我的查詢是:

@Repository
public interface MealRepository extends JpaRepository<Meal, Long> {
@Query(value ="select * from meal m where m.meal_type = ?1", nativeQuery = true)
List<Meal> findMealByType(MealType mealType);

}

但是當我對其進行測試時,我不斷收到org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet

除此之外,我還嘗試使用 MealType 作為參數重新編寫查詢:

  @Query(value ="select * from meal m where m.meal_type in :meal_type ", nativeQuery = true)
List<Meal> findMealByType(@Param("meal_type") MealType mealType);

但它引起了不同類型的錯誤

InvalidDataAccessResourceUsageException: could not prepare statement; SQL [select * from meal m where m.meal_type in ? ]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement

我預計其他地方會出現一些問題,但是基於 ID 搜索的相同自定義查詢可以正常工作。

您不能使用枚舉和 SQL。 您必須將參數作為字符串傳遞:

@Repository
public interface MealRepository extends JpaRepository<Meal, Long> {

    @Query(value ="select * from meal m where m.meal_type = ?1", nativeQuery = true)
    List<Meal> findMealByType(String mealType);
@Repository
public interface MealRepository extends JpaRepository<Meal, Long> {

    @Query(value ="select * from meal m where m.meal_type = :mealType", nativeQuery = true)
    List<Meal> findMealByType(@Param("mealType")MealType mealType);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM