AnilHoney
AnilHoney

Reputation: 249

How to write left join in hibernate?

I have following as table structure

**BPV table** 
  id, vid, bid

**vt table** 
   vid, name, gender

**uv table**
   uvid, vid, cast,...

i want to write left join between BPV ,uv based on vid in hibernate (mysql)

bpv entity have vt as one to one as well as uv have vt with one to one but there is no bpv &uv in realation

Upvotes: 1

Views: 1832

Answers (3)

Ziul
Ziul

Reputation: 893

What you're asking for is not posible, there is a Theta Join solution but it only supports inner join, so you have to give up on that approach and do one of the following solutions:

Map the proper relationship:

If this query is a unusual escenario, you dont necesary have to change your actual mapping , you can make a new dto Class with the new mapping, and use that one for this query.

Use native SQL:

This is prettly simple too, use .createSQLQuery(), to run the native query and you can use .addScalar() + .setResultTransformer(Transformers.aliasToBean(someDto.class)) to get a list of your entity.

Upvotes: 0

Juan Luis
Juan Luis

Reputation: 3357

Hibernate has Criteria API, which is a good way to execute queries in a OO approach. If you have your persistent entities, then you can do this:

Criteria criteria = session.createCriteria(BPV.class, "bpv");
criteria.createCriteria("bpv.vt", "vt", CriteriaSpecification.LEFT_JOIN);
criteria.createCriteria("vt.uv", "uv", CriteriaSpecification.LEFT_JOIN);
// add restrictions
return criteria.list();

Upvotes: 2

n00bot
n00bot

Reputation: 229

Hibernate SQL:

from BPV where BPV.uv.cast = "your_condition"

It requires properly described entities and dependency;

or pure SQL:

select * from BPV left join uv on BPV.vid = uv.vid where uv.cast = "your_condition"

Upvotes: 1

Related Questions