Executing string column as int in hql query or criteria
4 answers
You can do it with Hibernate Criteria
easily. For a solution, you have to create your own Hibernate Formula
for these (fromZip and toZip). The following should be your pojo mapping.
@Column
private String fromZip;
@Formula(value="to_number(fromZip)")
private double newfromZip;
@Column
private String toZip;
@Formula(value="to_number(toZip)")
private double newtoZip;
Below are your selection criteria:
Criteria criteria = session.createCriteria(ArcZipCodeRange.class);
criteria.add(Restrictions.le("newfromZip", yourIntegerParameter));
criteria.add(Restrictions.ge("newtoZip", yourIntegerParameter));
List<ArcZipCodeRange> list = criteria.list();
Hope this helps you.
+2
source to share
The below method helped me to type String for other data types using CriteriaBuilder.
CriteriaBuilder queryBuilder = em.getCriteriaBuilder();
Expression roomIdInt = queryBuilder.desc(root.get("room").get("id")).as(Integer.class));
//Expression roomIdInt = queryBuilder.desc(root.get("room").get("id")).as(Long.class));
//Expression roomIdInt = queryBuilder.desc(root.get("room").get("id")).as(Double.class));
//Expression roomIdInt = queryBuilder.desc(root.get("room").get("id")).as(Date.class));
//Expression roomIdInt = queryBuilder.desc(root.get("room").get("id")).as(Boolean.class));
At first I ran into many errors using CriteriaBuilder and tried to check the DB logs to check the query being executed. This helped fix the HQL as needed. The above approach works fine in PostgreSQL, but the solution varies depending on the database
0
source to share