Search code examples
jpajpa-2.0jpql

Casting Integer to String in JPQL


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?


Solution

  • 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>