【问题标题】:Custom queries in Spring Data JPASpring Data JPA 中的自定义查询
【发布时间】:2015-12-07 14:32:11
【问题描述】:

我在 JPA 中使用自定义查询,它不允许我使用 interval 关键字。如果我不在查询中使用- interval '7 days',它会给出正确的输出。

异常说: Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: interval near line 1, column 214

       @Query("select d from DomainName d , DomainNameReminder dr, Reseller  r"+
        " where d.reminder.id = dr.id  "+
        " and dr.secondNotification=current_date - interval '7 days' "+
        " and r.checkParty=true "+
        " and r.id = d.invoicingParty.id ")
        public List<Object> findDomainsBySecondNotificationDate();

这个查询基本上会带来所有在今天前 7 天具有第二个通知日期的记录。

我的接口声明为

public interface DomainNameRepository extends JpaRepository<DomainName, Long>, 
QueryDslPredicateExecutor<DomainName> {

我的查询在pgadmin postgresql client 中给出了正确的输出,我很惊讶为什么我不能在这里使用关键字。

【问题讨论】:

  • 此解决方案可能会对您的问题有所帮助。 stackoverflow.com/questions/1945615/…
  • JPQL 和 SQL 是两种不同的语言。尝试在 postgresql 客户端中使用 JPQL 查询(反之亦然)没有多大意义。
  • 您是否尝试将nativeQuery = true 添加到@Query 注释中?
  • 是的,因为 JPQL 中没有间隔之类的东西。那是 SQL 的事(甚至可能是 PostgreSQL 的事)。您不能期望 SQL 的每一个特性都存在于 JPQL 中:它们是不同的语言。
  • @reto 解决了我的问题 -> nativeQuery = true ,使用原生查询

标签: java spring postgresql spring-mvc spring-data-jpa


【解决方案1】:

这解决了我的问题。

我使用了nativeQuery=true 并使用了我在 postgresql 中执行的查询。也想与他人分享。

@Query( nativeQuery = true, value = "select domain_name.* from domain_name, domain_name_reminder, reseller " +
        "where domain_name.reminder_id = domain_name_reminder.id " +
        "and domain_name_reminder.second_notification=current_date - interval ':totalDays days' " +
        "and reseller.myCheck=true " +
        "and reseller.id = domain_name.invoicing_party_id ")
public List<DomainName> findDomainsBySecondNotificationDate(@Param("totalDays")Integer totalDays);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-25
    • 2012-09-13
    • 2019-03-10
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2020-02-11
    • 2021-04-01
    相关资源
    最近更新 更多