2012-06-12 90 views
-6

如何在hibernate中实现这个查询?如何在hibernate的两个表上实现查询数据?

select tab1.name from table1 tab1, table2 tab2 where table1.id = table2.id 
+0

要回答这个问题,我们需要查看映射table1和table2的实体。 – Pablo

+2

映射这些表的实体是什么?你有什么尝试?你在Hibernate文档中不理解什么? http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#queryhql-joins –

+0

table1包含列id,代码和table2包含id,name,repadd,repag。我需要从table2中挑选所有数据,无论id匹配。 –

回答

1

很好的解决:

有两个表之间的关系。这种关系是一对一,一对多,多对一或多对多的关系。在你的映射中创建这个关系。例如,如果table2是table1的子项,那么在table1类和映射中创建一个具有上述关系之一的属性,那么只需使用HQL语句“from table1”加载table1(使用可选的where-condition;也可选择加载可以指定两个表之间的内部连接),并且您使用table1.getTable2()(1:1或n:1关系)或table1.getTable2List()(1:n或n:m关系)访问表2。

草率的解决方案(但绝对OK,如果选择在特殊情况下只用):

不要在HQL select table1.col1, table1.col2, table2.col1 from table1 inner join table2 where ...和评估对象的数组列表,或者做select new Tabble1Table2Pojo(table1.col1, table1.col2, table2.col1) from table1 inner join table2 where ...和评估Tabble1Table2Pojo的列表。

+0

谢谢约翰娜。但我有疑问,我的hbm文件是怎么样的?可以üPLZ提供table1.hbm.xml和table2.hbm.xml代码片段? –

+0

看看这里:http://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/associations.html也有很多例子。 – Johanna

1

我想这会帮助你。

Criteria criteria = session.createCriteria(table1.class); 
criteria.setFetchMode("table2", FetchMode.JOIN).add(Restrictions.eq("id", 2)); 
ProjectionList proList = Projections.projectionList(); 
proList.add(Projections.property("name"), name); 
criteria.setProjection(proList); 
List list = criteria.list(); 
1

你必须使用投影API像

Criteria criteria = session.createCriteria(table1.class); 
criteria.setFetchMode("table2", FetchMode.JOIN).add(Restrictions.eq("id", 2)); 
ProjectionList proList = Projections.projectionList(); 
proList.add(Projections.property("name"), name); 
criteria.setProjection(proList); 
List list = criteria.list(); 

别名也没有在上面的例子中使用,但您可以使用别名,它的使用非常简单。

+0

嘿deepak,谢谢你的回复。但是,我的table1.hbm.xml和table2.hbm.xml是什么?我是否在table2.hbm.xml的table1.hbm.xml文件中保留了任何额外的配置? –

+0

准确地说,我不是不知道你在hbm文件中做了什么,但是,我认为不需要在hbm文件中更改/添加任何配置。 – Deepak

+0

另外,如果您参考Johanna的解决方案,那么您必须在hbm文件中更改或添加一些配置。我只是想说,在休眠中有很多解决方案可供您查询。 – Deepak

相关问题