like子句JPQL中的参数

时间:2009-08-27 13:29:24

标签: java jpa eclipselink jpql sql-like

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

LIKE '%:code%'

我想要代码= 4并找到

455
554
646
...

我无法通过:code = '%value%'

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

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

8 个答案:

答案 0 :(得分:161)

如果你这样做

LIKE :code

然后再做

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

然后价值保持不受'%'的影响。如果您需要在同一查询中的其他位置使用它,只需使用“代码”以外的其他参数名称。

答案 1 :(得分:52)

我没有为所有查询使用命名参数。例如,在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

答案 2 :(得分:7)

您可以使用JPA LOCATE function

  

LOCATE(searchString,candidateString [,startIndex]):返回   candidateString中searchString的第一个索引。职位从1开始。   如果找不到该字符串,则返回0。

仅供参考:my top google hit上的文档反转参数。

SELECT 
  e
FROM 
  entity e
WHERE
  (0 < LOCATE(:searchStr, e.property))

答案 3 :(得分:2)

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

String orgName = "anyParamValue";

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

q.setParameter("orgName", orgName);

答案 4 :(得分:2)

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%"));

答案 5 :(得分:1)

请忽略&#39;&#39;

LIKE %:code%

答案 6 :(得分:0)

  1. 使用下面的JPQL查询。

从讲师i中选择i,其中i.address类似于CONCAT('%',: address,'%')“);

  1. 在下面的条件代码中使用相同的代码:

    @测试   公共无效     findAllHavingAddressLike()     {CriteriaBuilder cb =      条件Utils.criteriaBuilder();      CriteriaQuery cq =      cb.createQuery(Instructor.class);     根=       cq.from(Instructor.class); printResultList(cq.select(根)    。哪里    (cb.like(root.get(Instructor_.address),     “%#1074%”))); }

答案 7 :(得分:0)

使用JpaRepositoryCrudRepository作为存储库接口:

@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());
    }
}