简体   繁体   English

枚举值的 Spring Boot JPA 本机查询

[英]Spring Boot JPA native query for enum values

I am trying to write a native query to search from a table based on EnumType entity.我正在尝试编写本机查询以从基于 EnumType 实体的表中进行搜索。 This ENUM MealType is a part of @Table Meal.此 ENUM MealType 是 @Table Meal 的一部分。

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

Now, my query is:现在,我的查询是:

@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);

} }

But when I run a test on it I keep getting 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 org.springframework.orm.jpa.JpaSystemException: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet

Apart from that, I have also tried to re-write the query with MealType as a parameter:除此之外,我还尝试使用 MealType 作为参数重新编写查询:

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

but it caused a different kind of error但它引起了不同类型的错误

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

I would expect that there is some problem somewhere else, but the same customized query with search based on ID works fine.我预计其他地方会出现一些问题,但是基于 ID 搜索的相同自定义查询可以正常工作。

You cannot use enums and SQL.您不能使用枚举和 SQL。 You have to pass the parameter as String:您必须将参数作为字符串传递:

@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