unnik
unnik

Reputation: 1153

Can I combine AND and OR conditions

I am using the below method to query using Spring Data JPA.

findByUpdatedGreaterThanAndFromEmailOrToEmailInOrderByUpdatedAsc(final long updated, final String email, final String to);

The query is always passes because of the OR condition.

My intention was findBy(UpdatedGreaterThan)And(FromEmailOrToEmailIn)OrderByUpdatedAsc

Is there anyway to do the same in Spring Data JPA.

Upvotes: 0

Views: 1693

Answers (1)

Marc Tarin
Marc Tarin

Reputation: 3169

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.

Upvotes: 1

Related Questions