简体   繁体   中英

How to search by field in embeded list of objects using Spring repository for Couchbase

I have following User Document:

@Document
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationStrategy.UNIQUE)
    private String id;

    @Field
    private String email;

    @Field
    private String fullName;

    @Field
    private LocalDate birthDate;

    @Field
    private Gender gender;

    @Field
    private List<Sport> sports = new ArrayList<>();
}

and Sport class:

@Data
public class Sport {

    private String id;

    private String sportName;

    private SportProficiency sportProficiency;

}

How can I create a method in UserRepository, to search for users by sport name? I have tried

@Query("#{#n1ql.selectEntity} unnest Users.sports s where s.sportName = $1")
List<User> findAllUsersBySportName(String sportName);

which gives me com.couchbase.client.core.error.ParsingFailureException: Parsing of the input failed

And

List<User> findAllBySports_SportName(String sportName);

which just builds an incorrect query and returns an empty list.

I came up with the following query:

@Query("#{#n1ql.selectEntity} where any s in Users.sports satisfies s.sportName in [$1] end;")
List<User> findAllUsersBySportName(String sportName);

This is not the best solution, but at least it's working. If you have a better solution, please post an answer.

which just builds an incorrect query and returns an empty list.

The generated query would have the predicate (sports.sportName = $1), which is correct for a property name sports of type Sport. But there is no syntax in the method naming for indicating that a property (sports) is a List.

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.query-methods.query-property-expressions

A slightly better query would use the predicate:

satisfies s.sportName = $1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM