[英]Parameter in like clause JPQL
我正在嘗試使用 like 子句編寫 JPQL 查詢:
LIKE '%:code%'
我想要 code=4 並找到
455 554 646 ...
我不能通過:code = '%value%'
namedQuery.setParameter("%" + this.value + "%");
因為在另一個地方我需要:value
沒有被%
字符包裹。 有什么幫助嗎?
如果你這樣做
LIKE :code
然后做
namedQuery.setParameter("code", "%" + this.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。
僅供參考: 我最熱門的 google上的文檔顛倒了參數。
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
或CrudRepository
作為存儲庫接口:
@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%
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.