Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL query join tables

Tags:

java

hql

I am using hibernate to connect to my database for a project.

I would like to have a query that gets the products out of my database with the discription and name in a certain language. The parameter I have is the short name for the language, so first I would have to get the id of the language and then get the text in the required languages.

I have tried the following hql query, without success.

from Products as p
where p.productlanguages.languages.shortname like 'eng'

This is an image of the part of the database where the data should come from: database

I have got the desired result with an sql query, but I can't seem to get it to work in hibernate. But I would prefer to do this in hql.

SELECT * FROM products p 
INNER JOIN productlanguage pl ON pl.Products_id = p.id 
WHERE pl.Languages_id = 
(
SELECT id FROM languages 
WHERE Shortname = 'eng'
);

Could anyone tell me how to build this hql query? Thank you.

like image 692
Jerodev Avatar asked Nov 06 '12 17:11

Jerodev


People also ask

How do I join two tables in HQL?

We can apply the Joins in Hibernate by using the HQL query or native SQL query. To make a join between the two tables, the two tables must be in a logical relationship. We can achieve the relationship between two tables by applying the parent table's primary key as a child table's foreign key.

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 write a left join in HQL?

select * from A as a left join B as b on a.id = b.id left join C as c on b. type=c.


1 Answers

Try below:

   from Products p INNER JOIN p.productlanguages pl
   where pl.languages.shortname ='eng'

I am assuming that you have mapped Product-Productlanguages relationship as OneToMany and Productlanguages-Langages relationship as ManyToOne as depicted in your E-R diagram.

EDIT: There seems to be a typo in Productlanguage mapping at line public Languages getLanguages() {barcode, remove the barcode in the end.

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="Languages_id", nullable=false, insertable=false, updatable=false)
public Languages getLanguages() {barcode

    return this.languages;
}
like image 157
Yogendra Singh Avatar answered Sep 29 '22 10:09

Yogendra Singh