[英]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.