Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Integer to String in JPQL

Tags:

jpa

jpql

jpa-2.0

I want to have a JPQL query that may look like:

    entityManager.createQuery("Select a.* from A a WHERE CAST(a.num AS TEXT) LIKE '%345%' ", A.class);

where a.num is an integer. I want to cast this to String to use the LIKE criteria. However above casting doesnt work in JPQL. Any idea about how can I implement this?

like image 858
Pratap Avatar asked Sep 13 '17 04:09

Pratap


3 Answers

Could you be more specific, what your problem is? Do you have some kind of error or it the result of the query is just wrong?

Because this code works fine for me:

session.createQuery("from MyObject where CAST(id as text) like :id").setParameter("id", "%1").getResultList();

I am using Hibernate 5.2 and Postgresql 9.5. Also, if you are having trouble understanding what goes wrong, you could try editing hibernate.cfg.xml or whatever configuration file you are using to make Hibernate show queries it sends, by doing something like this:

<property name="hibernate.show_sql">true</property>
like image 183
Stas Shafeev Avatar answered Oct 04 '22 14:10

Stas Shafeev


I also have the same need. This should work with JPA 2.0 and Hibernate 5.0.2:

entityManager.createQuery(
    "Select a.* from A a WHERE CONCAT(a.num, '') LIKE '%345%' ", A.class);
like image 32
Hendy Irawan Avatar answered Oct 04 '22 14:10

Hendy Irawan


From hibernate document, "cast(... as ...)", where the second argument is the name of a Hibernate type. According list of Hibernate Types it should be string (case sensitive!).

So request should be:

entityManager.createQuery("select a.* from A a WHERE CAST(a.num AS string) LIKE '%345%' ", A.class);

Was taken and checked from Caused by: org.hibernate.QueryException: Could not resolve requested type for CAST : INT answer.

like image 31
Grigory Kislin Avatar answered Oct 04 '22 14:10

Grigory Kislin