我正在尝试使用 like 子句编写 JPQL 查询:
LIKE '%:code%'
我想要 code=4 并找到
455 554 646 ...
我不能通过:code = '%value%'
namedQuery.setParameter("%" + this.value + "%");
因为在另一个地方我不需要被字符:value
包裹。%
有什么帮助吗?
我正在尝试使用 like 子句编写 JPQL 查询:
LIKE '%:code%'
我想要 code=4 并找到
455 554 646 ...
我不能通过:code = '%value%'
namedQuery.setParameter("%" + this.value + "%");
因为在另一个地方我不需要被字符:value
包裹。%
有什么帮助吗?
如果你这样做
LIKE :code
然后做
namedQuery.setParameter("code", "%" + this.value + "%");
然后 value 仍然没有 '%' 符号。如果您需要在同一查询中的其他地方使用它,只需使用 'code' 以外的另一个参数名称。
我不对所有查询使用命名参数。例如,在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
您可以使用JPA LOCATE 函数。
LOCATE(searchString, CandidateString [, startIndex]):返回候选字符串中 searchString 的第一个索引。位置是从 1 开始的。如果未找到该字符串,则返回 0。
仅供参考:我最热门的谷歌搜索文档中的参数颠倒了。
SELECT
e
FROM
entity e
WHERE
(0 < LOCATE(:searchStr, e.property))
我不知道我是迟到还是超出范围,但我认为我可以这样做:
String orgName = "anyParamValue";
Query q = em.createQuery("Select O from Organization O where O.orgName LIKE '%:orgName%'");
q.setParameter("orgName", orgName);
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%"));
使用JpaRepository
orCrudRepository
作为存储库接口:
@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());
}
}
select i from Instructor i where i.address LIKE CONCAT('%',:address ,'%')");
@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%")));
}
只需省略''
LIKE %:code%