問題描述
我可以結合 AND 和 OR 條件嗎 (Can I combine AND and OR conditions)
我正在使用以下方法使用 Spring Data JPA 進行查詢。
findByUpdatedGreaterThanAndFromEmailOrToEmailInOrderByUpdatedAsc(final long updated, final String email, final String to);
由於 OR 條件,查詢總是通過。
我的意圖是 findBy( UpdatedGreaterThan)And(FromEmailOrToEmailIn)OrderByUpdatedAsc
在 Spring Data JPA 中是否也可以這樣做。
參考解法
方法 1:
You can use the @Query annotation to manually craft a mongodb query to properly enforce the logic of your search criteria.
Something like (I leave the ordering part to you):
@Query(
"{ $and : [ { 'updated' : { $gt: '?0'} }," +
"{ $or : [ { 'email' : '?1' }, { 'to' : '?2' } ] }")
findByUpdatedGreaterThanAndFromEmailOrToEmailInOrderByUpdatedAsc(final long updated, final String email, final String to);
where ?0, ?1, ?2 are placeholders for your findBy method arguments.
(by unnik、Marc Tarin)