我已经定义了我的 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 引用文档,但找不到任何关于通配符和 @query
的信息。 .以下 hack 有效,但有点难看:
and lower(c.fullName) like '%' || lower(:name) || '%'
有没有人有更好的解决方案?
谢谢,
缪尔。
最佳答案
我也不会称其为 hack - 这是针对这些问题定义 JPQL 语法的方式。
但是,还有一个使用 CriteriaBuilder/CriteriaQuery 的替代方法。 ,但也许你会发现它更复杂(但你会得到编译时类型安全的返回)。
关于jpa-2.0 - 是否可以向@Query 参数添加通配符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11623113/