Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPQL: cast Long to String to perform LIKE search

I have the following JPQL query:

SELECT il
FROM InsiderList il
WHERE ( il.deleteFlag IS NULL OR il.deleteFlag = '0' )
  AND il.clientId = :clientId
  AND (    LOWER( il.name ) LIKE :searchTerm
        OR il.nbr LIKE :searchTerm
        OR LOWER( il.type ) LIKE :searchTerm
        OR LOWER( il.description ) LIKE :searchTerm )

The customer wants us to be able to search be the nbr field, which is a java.lang.Long.

Q:

How do you perform a LIKE search on a java.lang.Long using JPQL?

like image 322
Kawu Avatar asked Jun 26 '15 17:06

Kawu


People also ask

Which of the following methods is used to execute a select JPQL query?

Query createQuery(String name) - The createQuery() method of EntityManager interface is used to create an instance of Query interface for executing JPQL statement.

Does JPQL support limit?

As mentioned earlier, JPQL doesn't support LIMIT and OFFSET clauses. But you can use the same setFirstResult and setMaxResults methods of the Query and TypedQuery interface that I showed you in the previous section. . getResultList();

What do you understand by JPQL query?

The Jakarta Persistence Query Language (JPQL; formerly Java Persistence Query Language) is a platform-independent object-oriented query language defined as part of the Jakarta Persistence (JPA; formerly Java Persistence API) specification. JPQL is used to make queries against entities stored in a relational database.


2 Answers

You can simply use CAST(num as string) or CONCAT(num,''). It worked for me

like image 165
Amit Jain Avatar answered Sep 19 '22 12:09

Amit Jain


You can use the CAST in HQL:

SELECT il
FROM InsiderList il
WHERE ( il.deleteFlag IS NULL OR il.deleteFlag = '0' )
  AND il.clientId = :clientId
  AND (    LOWER( il.name ) LIKE :searchTerm
        OR CAST( il.nbr as string ) LIKE :searchTerm
        OR LOWER( il.type ) LIKE :searchTerm
        OR LOWER( il.description ) LIKE :searchTerm )

But you can have serious performance problems doing this, because the database will cannot use the nbr index (if nbr column is indexed).

like image 23
Dherik Avatar answered Sep 20 '22 12:09

Dherik