I am trying to write a JPQL query with a like clause:
LIKE \'%:code%\'
I would like to have code=4 and find
455 554 646 ...
I don't know if I am late or out of scope but in my opinion I could do it like:
String orgName = "anyParamValue";
Query q = em.createQuery("Select O from Organization O where O.orgName LIKE '%:orgName%'");
q.setParameter("orgName", orgName);
Use JpaRepository
or CrudRepository
as repository interface:
@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());
}
}
Just leave out the ''
LIKE %:code%
You could use the JPA LOCATE function.
LOCATE(searchString, candidateString [, startIndex]): Returns the first index of searchString in candidateString. Positions are 1-based. If the string is not found, returns 0.
FYI: The documentation on my top google hit had the parameters reversed.
SELECT
e
FROM
entity e
WHERE
(0 < LOCATE(:searchStr, e.property))
There is nice like() method in JPA criteria API. Try to use that, hope it will help.
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%"));
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%")));
}