是否可以向@Query参数添加通配符?

时间:2012-07-24 02:05:54

标签: jpa-2.0 spring-data spring-data-jpa

我已将ContactDao定义如下:

public interface ContactDao extends JpaRepository<Contact, Long> {

  /**
   * Finds all contacts that the given user has entered where the contact's full name matches {@code name}.
   * @param userId The current user's LDAP id.
   * @param name The name to search for.
   * @return A list of contacts matching the specified criteria.
   */
  @Query(" select c from Form as f" +
           " inner join f.contacts as c" +
           " where f.requestorUserId = :userId" +
           " and lower(c.fullName) like lower(:name)" +
           " order by lower(c.fullName)")
  List<Contact> findUserContactsByUserIdAndName(@Param("userId") String userId, @Param("name") String name);

}

以上工作正常,我生成的SQL就是我自己编写的。问题是我想在:name参数中添加周围的通配符。有什么好办法吗?我已经看过Spring Data JPA参考文档了,我找不到任何关于wildards和@query的内容。

以下黑客有效,但有点难看:

and lower(c.fullName) like '%' || lower(:name) || '%'

有没有人有更好的解决方案?

谢谢, 道穆埃尔。

1 个答案:

答案 0 :(得分:3)

我也不会称之为黑客 - 这就是为这些问题定义JPQL语法的方式。

但是,有一个使用CriteriaBuilder/CriteriaQuery的替代方法,但是你可能发现它更复杂(但是你得到了编译时类型的安全性)。