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

标签 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 引用文档,但找不到任何关于通配符和 @query 的信息。 .

以下 hack 有效,但有点难看:
and lower(c.fullName) like '%' || lower(:name) || '%'

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

谢谢,
缪尔。

最佳答案

我也不会称其为 hack - 这是针对这些问题定义 JPQL 语法的方式。

但是,还有一个使用 CriteriaBuilder/CriteriaQuery 的替代方法。 ,但也许你会发现它更复杂(但你会得到编译时类型安全的返回)。

关于jpa-2.0 - 是否可以向@Query 参数添加通配符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11623113/

相关文章:

java - 没有连接表的多对多关联

java - JPA查询不在子查询关系表中

jpa-2.0 - 无法从 HSQLDB 生成 JPA 实体

java - Springboot Jpa更新记录而不是插入

java - 使用 JOIN 实现 JPA 请求

java - 如何通过 spring-data-jpa 框架进行自定义搜索?

spring-boot - 从 redis 中删除键/值 - 幻键未删除

spring - 过期key触发事件-Spring data Redis

spring-boot - 如何编写 JPA IN 查询来检查集合是否具有给定的值集?

java - Spring Data 中的自定义方法实现失败并出现属性未找到错误