Spring数据查询有条件吗?

Are there conditions in Spring data queries?

我有一个 Spring 存储库界面和以下方法来按 organizationalUnittype.

查找人员
public interface PersonRepository extends CrudRepository<Person, Integer> {

    @Query("SELECT p FROM Person p "
        + "JOIN p.organizationalUnit ou "
        + "JOIN p.type type "
        + "WHERE p.name = ?1 "
        + "AND ou = ?2 "
        + "AND type = ?3")
    List<Person> filterPerson(String name, OrganizationalUnit u, Type t);
}

上面的代码工作正常,但是如果 ut 的给定值是 null 我需要找到所有的人,不管他们的类型或单位如何。

有没有一种方法可以根据条件声明语句?

类似于:

@Query("SELECT p FROM Person p "
        + "JOIN p.organizationalUnit ou "
        + "JOIN p.type type "
        + "WHERE p.name = ?1 "
        + {?2 != null ? "AND ou = ?2 " : ""}
        + {?3 != null ? "AND type = ?3 " : ""}
        )

你可以简单地这样做:

@Query("SELECT p FROM Person p "
        + "JOIN p.organizationalUnit ou "
        + "JOIN p.type type "
        + "WHERE p.name = ?1 "
        + "AND (?2 is null OR ou = ?2)"
        + "AND (?3 is null OR type = ?3)"
        )