Casting Integer to String in JPQL

左心房为你撑大大i 提交于 2019-12-10 14:15:20

问题


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?


回答1:


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>



回答2:


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



回答3:


The correct query is : entityManager.createQuery("Select a.* from A a WHERE CAST(a.num AS String) LIKE '%345%' ", A.class);




回答4:


Well you can use to_char() function in the select clause but, you will need to select all the a.num field separately and not with *.

And in postgresql you will need to specify a mask for to_char()function, so it would be to_char(field, mask), for example we can supply 'FM999999999999999999' as a mask to accept the maximum possible digits.

Your query would be something like this:

Select *, to_char(a.num, 'FM999999999999999999') as num from A a WHERE num LIKE '%345%'

You can take a look at Postgresql Data Type Formatting Functions for further details.

To write the query in your code with EntityManager you can create a native query using .createNativeQuery() method, this is how should be your code:

em.createNativeQuery("Select *, to_char(a.num, 'FM999999999999999999') as num from A a WHERE num LIKE '%345%'");



回答5:


You can simply use CAST(num as string). It worked for me




回答6:


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.



来源:https://stackoverflow.com/questions/46188918/casting-integer-to-string-in-jpql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!