【问题标题】:Spring Data JPA - multiple OR clausesSpring Data JPA - 多个 OR 子句
【发布时间】:2016-11-15 06:42:25
【问题描述】:

考虑以下几点:

interface TicketRepository extends JpaRepository<Ticket, Integer> {
    List<Ticket> findByOpenDateBetweenOrCloseDateBetweenAndPersonIdAndType(Timestamp start1, Timestamp end1, Timestamp start2, Timestamp end2, Integer personId, TicketType type)
}

生成如下SQL:

select
    ticket0_.id as id1_10_,
    ticket0_.close_date as close_da2_10_,
    ticket0_.complaint as complain3_10_,
    ticket0_.connection_id as connecti4_10_,
    ticket0_.district_id as district5_10_,
    ticket0_.open_date as open_dat6_10_,
    ticket0_.person_id as person_i7_10_,
    ticket0_.public_id as public_i8_10_,
    ticket0_.ticket_queues_id as ticket_q9_10_,
    ticket0_.ticket_statuses_id as ticket_10_10_,
    ticket0_.ticket_types_id as ticket_11_10_,
    ticket0_.users_id as users_i12_10_ 
from
    ticket_tickets ticket0_ 
left outer join
    ticket_types tickettype1_ 
        on ticket0_.ticket_types_id=tickettype1_.id 
where
    ticket0_.open_date between ? and ? 
    or (
        ticket0_.close_date between ? and ?
    ) 
    and ticket0_.person_id=? 
    and tickettype1_.id=?

我需要的是两个 BETWEEN 都在同一个括号中,如下所示:

( ticket0_.open_date between ? and ? OR ticket0_.close_date between ? and ? )

有没有一种方法我可以通过更改方法名称来做到这一点,或者我必须采用自定义 @Query 方法?

【问题讨论】:

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


    【解决方案1】:

    使用 @Query 方法。这要简单得多。应该使用查询构建器机制来编写简单的查询。您还将提高代码的可读性。

    【讨论】:

    • 将其标记为答案,因为这是我最终要做的...但是知道一种控制查询中 OR 子句的方法仍然会很有趣...即使是更简单的方法,例如"findBy(ThisOrThis)AndThat"
    • 谢谢!我可以告诉你我在回答之前搜索了很多,并且我在一个查询中遇到了类似的问题,我必须搜索 3 个可选参数。我把我能找到的所有教程和文档都涂红了,我什至在书中搜索,但我从来没有找到如何做到这一点。我认为查询构建器机制的开发是为了编写非常简单的查询,就像你在 spring 文档中找到的那样:docs.spring.io/spring-data/jpa/docs/1.4.3.RELEASE/reference/…
    猜你喜欢
    • 2020-01-16
    • 2016-04-29
    • 2018-01-21
    • 2017-01-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2015-09-20
    • 2016-11-26
    相关资源
    最近更新 更多