98

我正在尝试使用 like 子句编写 JPQL 查询:

LIKE '%:code%'

我想要 code=4 并找到

455
554
646
...

我不能通过:code = '%value%'

namedQuery.setParameter("%" + this.value + "%");

因为在另一个地方我不需要被字符:value包裹。%有什么帮助吗?

4

8 回答 8

173

如果你这样做

LIKE :code

然后做

namedQuery.setParameter("code", "%" + this.value + "%");

然后 value 仍然没有 '%' 符号。如果您需要在同一查询中的其他地方使用它,只需使用 'code' 以外的另一个参数名称。

于 2009-08-27T22:57:30.487 回答
60

我不对所有查询使用命名参数。例如,在JpaRepository中使用命名参数是不常见的。

要解决方法,我使用 JPQL CONCAT函数(此代码模拟以 开头):

@Repository
public interface BranchRepository extends JpaRepository<Branch, String> {
    private static final String QUERY = "select b from Branch b"
       + " left join b.filial f"
       + " where f.id = ?1 and b.id like CONCAT(?2, '%')";
    @Query(QUERY)
    List<Branch> findByFilialAndBranchLike(String filialId, String branchCode);
}

我在优秀的文档中发现了这种技术:http: //openjpa.apache.org/builds/1.0.1/apache-openjpa-1.0.1/docs/manual/jpa_overview_query.html

于 2013-04-05T16:28:26.527 回答
7

您可以使用JPA LOCATE 函数

LOCATE(searchString, CandidateString [, startIndex]):返回候选字符串中 searchString 的第一个索引。位置是从 1 开始的。如果未找到该字符串,则返回 0。

仅供参考:我最热门的谷歌搜索文档中的参数颠倒了。

SELECT 
  e
FROM 
  entity e
WHERE
  (0 < LOCATE(:searchStr, e.property))
于 2016-05-23T21:58:52.770 回答
4

我不知道我是迟到还是超出范围,但我认为我可以这样做:

String orgName = "anyParamValue";

Query q = em.createQuery("Select O from Organization O where O.orgName LIKE '%:orgName%'");

q.setParameter("orgName", orgName);
于 2017-12-20T10:13:40.900 回答
3

JPA 标准 API 中有一个不错的 like() 方法。尝试使用它,希望它会有所帮助。

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery criteriaQuery = cb.createQuery(Employees.class);
Root<Employees> rootOfQuery = criteriaQuery.from(Employees.class);
criteriaQuery.select(rootOfQuery).where(cb.like(rootOfQuery.get("firstName"), "H%"));
于 2018-08-16T21:01:05.160 回答
2

使用JpaRepositoryorCrudRepository作为存储库接口:

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {

    @Query("SELECT t from Customer t where LOWER(t.name) LIKE %:name%")
    public List<Customer> findByName(@Param("name") String name);

}


@Service(value="customerService")
public class CustomerServiceImpl implements CustomerService {

    private CustomerRepository customerRepository;
    
    //...

    @Override
    public List<Customer> pattern(String text) throws Exception {
        return customerRepository.findByName(text.toLowerCase());
    }
}
于 2020-08-15T14:44:24.487 回答
2
  1. 使用下面的 JPQL 查询。
select i from Instructor i where i.address LIKE CONCAT('%',:address ,'%')");
  1. 使用下面的标准代码相同:
@Test
public void findAllHavingAddressLike() {
    CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
    CriteriaQuery<Instructor> cq = cb.createQuery(Instructor.class);
    Root<Instructor> root = cq.from(Instructor.class);
    printResultList(cq.select(root).where(
        cb.like(root.get(Instructor_.address), "%#1074%")));
}
于 2019-01-28T21:46:49.753 回答
0

只需省略''

LIKE %:code%
于 2017-06-01T16:56:57.053 回答