Spring数据查询中是否存在条件?

时间:2016-07-11 13:33:33

标签: java spring spring-data-jpa

我有一个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 " : ""}
        )

1 个答案:

答案 0 :(得分:1)

你可以这样做:

@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)"
        )