简体   繁体   English

如何使用hibernate条件实现使用内部联接对象选择查询

[英]How to implement with hibernate criteria Object the select query with inner join

I'm new with Hibernate and Criteria Query. 我是Hibernate和Criteria Query的新手。 So I have implemented the query in HQL: 所以我在HQL中实现了查询:

select A.mobilephone
    B.userNick
    C.creditCard
from mobile_table A
inner join user_table B
    on A.codmobile=B.codmobile
inner join Credit C 
    on A.mobileCredit= C.mobileCredit

How can I implement it with Hibernate Criteria Object? 如何使用Hibernate Criteria Object实现它?

Your example is just a native SQL , not the HQL . 您的示例只是本机SQL,而不是HQL。 Anyway , you can use the following methods from the Criteria API to construct the desired Criteria object : 无论如何,您可以使用Criteria API中的以下方法来构造所需的Criteria对象:

For example , if the SQL is : 例如,如果SQL是:

select
    TableA.columnA ,TableB.columnB ,TableC.columnC
from TableA 
inner join TableB on TableA.tableB_id=TableB.id
inner join TableC on TableA.tableC_id=TableC.id
where TableA.columnAA="AAA"
and TableB.columnBB="BBB"
and TableC.columnCC="CCC"

Then the Criteria object will be: 那么Criteria对象将是:

List<Object[]>resultList= (List<Object[]>)session.createCriteria(TableA.class, "aliasOfTableA") 
                .add(Restrictions.eq("aliasOfTableA.columnAA", "AAA"))  
                .createCriteria("aliasOfTableA.tableBId" , "aliasOfTableB")
                .add(Restrictions.eq("aliasOfTableB.columnBB", "BBB"))
                .createCriteria("aliasOfTableA.tableCId" , "aliasOfTableC")
                .add(Restrictions.eq("aliasOfTableC.columnCC", "CCC"))
                .setProjection( Projections.projectionList()
                        .add( Projections.property("aliasOfTableA.columnA") )
                        .add( Projections.property("aliasOfTableB.columnB"))
                        .add( Projections.property("aliasOfTableC.columnC") )
                ).list();

for (Object[] obj : resultList) {
        System.out.println(obj[0]); //print the value from TableA.columnA
        System.out.println(obj[1]); //print the value from TableB.columnB
        System.out.println(obj[2]); //print the value from TableC.columnC
}   

Please note that all parameters in the Criteria use the property name and class name in the mapped Java entities. 请注意, Criteria中的所有参数都使用映射的Java实体中的属性名称和类名称。

Are you sure that's HQL? 你确定那是HQL吗? Looks like native SQL to me. 对我来说看起来像本机SQL。

In order to use Criteria your entities need to be mapped and associated with each other (since Criteria only allows navigating association paths). 为了使用Criteria,您的实体需要映射并相互关联(因为Criteria只允许导航关联路径)。 I think you could get more help if you give some details about your mappings. 如果您提供有关映射的详细信息,我想您可以获得更多帮助。

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

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