是否可以在@Query
注释中调用参数的方法?
示例:
@Query("SELECT user " +
"FROM User user " +
"WHERE (?1.getFilter() = '*' OR user.name = ?1)");
List<User> getUsers(UserNameFilter userNameFilter);
我知道我可以这样做:
@Query("SELECT user " +
"FROM User user " +
"WHERE (?1 = '*' OR user.name = ?1)");
List<User> getUsers(String userName);
但是当大量过滤器增加时,意味着我需要更改一些参数。
答案 0 :(得分:3)
使用SpEL,您可以在查询中使用Spring bean方法,例如
@Query("select e from MyEntity e where ?#{@myBean.myMethod(#param1)} is true")
List<MyEntity> entities = getEntity(@Param("param1") String param);
您可以以任何正确的方式定义bean,例如:
@Component
public class MyBean {
public boolean myMethod(String param) {...}
}
或者它甚至可以是相同的回购:
public interface MyRepo extends JpaRepository<MyEntity, Long> {
@Query("select e from MyEntity e where ?#{@myRepo.myMethod(#param1)} is true")
List<MyEntity> entities = getEntity(@Param("param1") String param);
default boolean myMethod(String param) {...}
}
您还可以在查询中使用参数属性:
@Query("select u from User u where u.firstname = ?#{#customer.firstname}")
List<User> findUsersByCustomersFirstname(@Param("customer") Customer customer);