我是Hibernate和Criteria Query的新手。所以我在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
如何使用hibernate条件对象实现它?
您的示例只是本机SQL,而不是HQL。无论如何,您可以使用Criteria API中的以下方法来构造所需的Criteria对象:
例如,如果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"
那么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 }
请注意,所有参数Criteria使用映射的Java实体中的属性名称和类名称。
Criteria