我有一个Spring存储库接口和以下方法,可以通过organizationalUnit
和type
查找人员。
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);
}
上述代码运行正常,但如果u
或t
的给定值为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 " : ""}
)
答案 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)"
)