简体   繁体   English

如何在休眠状态下使用join从三个表中获取记录?

[英]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. 我在mysql中使用了此命令,并轻松检索了我的记录,但是我无法在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). 如何使用hibernate(条件或HQL)在Java中执行此操作。

In Hibernate you have to think in Objects (OO). 在Hibernate中,您必须考虑对象(OO)。 So your tables in your query should be changed to Entities. 因此,查询中的表应更改为Entities。 Etc. Hibernate will only allow joins between tables, if the relations between the tables (Entities) are defined in the Entities. 如果表(实体)之间的关系在实体中定义,则Hibernate等仅允许表之间的联接。 (Eg by annotations like @OneToMany) (例如,通过@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"): 因此,如果定义了必要的关系,则HQL类似于(假设您联接的2个表通过Hibernate通过“ 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 . 如果您不希望Hibernate返回Entities,则应签出ResultTransformer,例如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. 您要了解的一件事是:不要将Hibernate视为访问数据库的另一种语言。 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 假设您已经为表1-3适当映射了实体(我们将实体称为Foo1,Foo2和Foo3),并且您也已正确映射了关系,则HQL应该看起来像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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