简体   繁体   中英

how can get records from three tables using join in hibernate?

I used this command in mysql and retrieved my records easily, but I am unable to do it in Java. Please advice.

select * from table1 
   LEFT JOIN table2 ON table1.FRID=table2.FRID 
   LEFT JOIN table3 ON table1.FRID=table3.FRID 
 where table1.FRID='000000338';

How can I do this in Java using hibernate(criteria or HQL).

In Hibernate you have to think in Objects (OO). So your tables in your query should be changed to Entities. Etc. Hibernate will only allow joins between tables, if the relations between the tables (Entities) are defined in the Entities. (Eg by annotations like @OneToMany)

So, if the necessary relations are defined, HQL would be something like (assuming that the 2 tables you join on, are linked/mapped via Hibernate with "table1"):

from Table1Class as table1alias
left join fetch Table2Class
left join fetch Table3Class
where table1alias.idPropertyInTable1Class = '000000338'

If you don't want Hibernate to return Entities, you should check out ResultTransformer, like for example here .

There is no meaningful answer unless you show your mapping.

One thing that you want to be aware is: don't see Hibernate as another language to access DB. You should see it as an Object Relational Mapping tools. Once you have the mapping done, in most case you should work with your domain model, instead of thinking of DB tables.

Assuming you have already appropriately mapped your entity for Table1-3 (let's call the entities Foo1, Foo2 and Foo3), and you have relationship mapped appropriately too, the HQL should looks like

select foo from Foo1 foo
left join fetch foo.foo2
left join fetch foo.foo3
where foo.id = '000000338'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM