Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write hql query with cast?

I need to combine 2 tables using hql, both are having common column, but table1 common column is integer and table2 common column is String

For example,

select a.id as id,a.name as name,b.address as address 
from Personal as a,Home as b 
where a.id=b.studid

Here a.id is an integer while b.stduid is a string, but Data of both columns is the same.

How can I get the result of the query using hql query?

like image 920
ver Avatar asked Jan 25 '11 08:01

ver


People also ask

Can we use join in HQL query?

Some of the commonly supported clauses in HQL are: HQL From: HQL From is same as select clause in SQL, from Employee is same as select * from Employee . We can also create alias such as from Employee emp or from Employee as emp . HQL Join : HQL supports inner join, left outer join, right outer join and full join.

How do I concatenate in HQL?

You may create a calculated column in your entity: @Formula(value = " concat(first_name, ' ', last_name) ") private String fullName; And in your HQL you just refer to this field as you would do to any other.


2 Answers

HQL supports CAST (if underlying database supports it), you can use it:

select a.id as id,a.name as name,b.address as address  from Personal as a,Home as b where cast(a.id as string) = b.studid  

See also:

  • 16.10. Expressions
like image 78
axtavt Avatar answered Oct 07 '22 00:10

axtavt


You really need to think why have you got a need to join two entities by properties of different types. Most likely it suggests that some of the entities need to be refactored, which could include changing data types for columns of the underlying db tables. If the model is correct there will be no need to twist Hibernate.

like image 38
01es Avatar answered Oct 07 '22 00:10

01es