javasqlspringjpafindby

Please, suggest custom findBy or query


I need to do a search by several parameters, but if some of them are null don't take them into account when searching. For example, I want to find a person who is in the USA and works in Google, but now my search is implemented so that there are all who are now in the USA or who are currently working on Google. And if I use and instead of or, the fields will be searched with null.

Now my search looks like this and gets a set on the input - from which the second question arises. How can I compare this set with the OneToMany table of this entity?

Long<Game> findByGameTitleOrGameTypeOrGameLocations(String title, String type, Set<String> locations);

This is set of locations from the entity:

@ElementCollection
private Set<String> gameLocations;

These questions may seem silly to someone xD But I'm a newbie.


Solution

  • I can suggest custom query requests by @Query annotation. I am not sure that it is the optimal way, but it works.

    @Query("SELECT g FROM Game g" +
        " WHERE (:title is null or g.title = :title)" +
        " AND (:type is null or g.type = :type)" +
        " AND (:locations is null or g.locations in :locations)")
    Long<Game> findByGameTitleOrGameTypeOrGameLocations(
        @Param("title") String title,
        @Param("type") String type,
        @Param("locations") Set<String> locations);
    

    It is an example of a request because I don't know your DB model exactly.