【问题标题】:Spring Data - Customer @Query with no property matchingSpring Data - 没有属性匹配的客户@Query
【发布时间】:2013-03-28 12:13:56
【问题描述】:

我正在尝试设置一个不会自动生成的自定义 @Query,但无论我尝试什么,它都会尝试将方法名称中的属性与返回对象中的属性相匹配。

如何在不尝试构建查询的情况下运行此查询,并因 org.springframework.data.mapping.PropertyReferenceException 而失败?也许@Query 是错误的注解?

我的仓库目前看起来像这样:

@Repository
public interface ScheduleRepository extends CrudRepository<Schedule, Integer>
{
    @Query
    List<Schedule> findByTypeAndAirDateBetweenOrderByAirDateDesc(String type, Date startDate, Date endDate);

    @Query("SELECT s FROM Schedule s WHERE s.type = 'A' AND (s.airDate BETWEEN :startDate AND :endDate) ORDER BY ABS(DATEDIFF(s.airDate, NOW())) LIMIT 1")
    List<Schedule> findCurrentAd(Date startDate, Date endDate);
}

当它在我的 Schedule 类中找不到匹配的“当前”字段时会发生异常。我不希望它。我只希望它按照我的定义运行查询,不问任何问题。

您可能已经看出,我是 Spring MVC 和数据的新手。

感谢大家的帮助!

【问题讨论】:

  • 我的回答解决了你的问题吗@Dave V?

标签: hibernate spring-mvc spring-data spring-data-jpa


【解决方案1】:

如果您使用绑定参数,例如:VALUE,您应该使用@Param("value") 来匹配您的@Query 注释。试试这个:

@Repository
public interface ScheduleRepository extends CrudRepository<Schedule, Integer>
{
    @Query
    List<Schedule> findByTypeAndAirDateBetweenOrderByAirDateDesc(String type, Date startDate, Date endDate);

    @Query("SELECT s FROM Schedule s WHERE s.type = 'A' AND (s.airDate BETWEEN :startDate AND :endDate) ORDER BY ABS(DATEDIFF(s.airDate, NOW())) LIMIT 1")
    List<Schedule> findCurrentAd(@Param("startDate") Date startDate, @Param("endDate") Date endDate);
}

如果你选择使用没有@Param注解的构造函数,你可以像这样使用?n绑定:

@Repository
public interface ScheduleRepository extends CrudRepository<Schedule, Integer>
{
    @Query
    List<Schedule> findByTypeAndAirDateBetweenOrderByAirDateDesc(String type, Date startDate, Date endDate);

    @Query("SELECT s FROM Schedule s WHERE s.type = 'A' AND (s.airDate BETWEEN ?1 AND ?2) ORDER BY ABS(DATEDIFF(s.airDate, NOW())) LIMIT 1")
    List<Schedule> findCurrentAd(Date startDate, Date endDate);
}

?n 绑定表示方法中的参数序列。 ?1 = 开始日期,?2 = 结束日期。

参考:Spring Docs

【讨论】:

    猜你喜欢
    • 2019-05-29
    • 2017-12-18
    • 1970-01-01
    • 2021-03-13
    • 2021-10-10
    • 2020-05-02
    • 2013-06-11
    相关资源
    最近更新 更多