java - Spring Boot JPA 本机查询枚举值
问题描述
我正在尝试编写一个本机查询来从基于 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 搜索的相同自定义查询可以正常工作。
解决方案
您不能使用枚举和 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);