我可以結合 AND 和 OR 條件嗎 (Can I combine AND and OR conditions)


問題描述

我可以結合 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 unnikMarc Tarin)

參考文件

  1. Can I combine AND and OR conditions (CC BY‑SA 2.5/3.0/4.0)

#spring-data-mongodb #spring-data-jpa






相關問題

如何在 mongodb 中保存 java.sql.date 對象? (How to save java.sql.date object in mongodb?)

Spring Data MongoDB Core 1.9.1.RELEASE 給出 java.lang.NoClassDefFoundError: org/springframework/data/geo/GeoResults (Spring Data MongoDB Core 1.9.1.RELEASE gives java.lang.NoClassDefFoundError: org/springframework/data/geo/GeoResults)

我可以結合 AND 和 OR 條件嗎 (Can I combine AND and OR conditions)

查詢數據時應該使用 MongoTemplate 還是 DBCollection (Should i use MongoTemplate or DBCollection when query data)

是否有可能使用 Spring Data MongoDb 來定義自定義標準? (Is possibility using Spring Data MongoDb to define custom Criteria?)

Spring-data 2.1 使用 kotlin 獲取“UnsupportedOperationException:沒有訪問器設置屬性” (Spring-data 2.1 get "UnsupportedOperationException: No accessor to set property" with kotlin)

調用頁面大小大於 36 的 Spring Data MongoDB 存儲庫方法時出現 StackOverflowError (StackOverflowError when calling Spring Data MongoDB repository method with a page size bigger than 36)

JSON- MongoDB 中帶有 Spring Data 的數組 (JSON- Array in MongoDB with Spring Data)

Spring Data Mongo DB:回复消息長度5502322小於最大消息長度 (Spring Data Mongo DB: The reply message length 5502322 is less than the maximum message length)

Spring Boot 反應式和 mongodb '命令插入需要身份驗證' (Spring boot reactive and mongodb 'command insert requires authentication')

使用 MongoDB Spring Data Aggregation 匹配日期時間字段的問題 (Problem with matching date-time fields using MongoDB Spring Data Aggregation)

在 Spring Boot 應用程序中實現工作進程 (Implementing worker processes in a Spring Boot application)







留言討論