【问题标题】:Spring Boot JPA native query for enum valuesSpring Boot JPA 本机查询枚举值
【发布时间】:2020-04-15 11:32:36
【问题描述】:

我正在尝试编写一个本机查询来从基于 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

除此之外,我还尝试使用 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 搜索的相同自定义查询可以正常工作。

【问题讨论】:

  • 你试过List&lt;Meal&gt; findMealByType(String mealType);吗?
  • 但我需要将 Enum 作为参数传递
  • @VladDemyan 你为什么使用nativeQuery
  • 你用的是spring data jpa,为什么不findByMealType(MealType mealType);没什么好补充的。

标签: java spring jpa spring-data-jpa


【解决方案1】:

您不能使用枚举和 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);

【讨论】:

【解决方案2】:
@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);
}

【讨论】:

  • "m.mealType = :mealType" ? @chillworld
  • 通过解释您的答案如何解决相关问题来添加一些上下文,而不是发布仅代码的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 1970-01-01
  • 2021-07-27
  • 2015-08-22
  • 1970-01-01
  • 2021-10-13
  • 1970-01-01
相关资源
最近更新 更多