hibernate select 选择列 返回bean

原文地址:

http://www.javalobby.org/articles/hibernate-query-101/

HibernateQuerying101:tipsandtricks

查询条件

Stringquery=

"selectcom.id,com.label,com.postCode,com.mayor.name

fromCommunityascom

leftjoincom.mayor

orderbycom.label";

results=HibernateUtils.find(query);

publicListfind(finalStringhqlQuery)throwsException{

Listresults=newArrayList();

//

//PrepareaHibernatequery

//

Queryquery=SessionManager.currentSession().createQuery(hqlQuery);

//

//Determinethereturntypeforthisquery

//

TypebeanType=query.getReturnTypes()[0];

ClassbeanClass=beanType.getReturnedClass();

//

//Extractthelistofcolumnsreturnedbythisquery

//

String[]columns=extractColumns(hqlQuery);

//

//Pre-processbeanattributenames,strippingspaces'as'clauses

//

String[]attributeNames=getAttributeFieldNames(columns);

//

//Pre-processresultfieldnames,strippingspacesandretaining

//aliasfieldnamesinsteadoftheoriginalcolumnnameswherenecessary

//

String[]resultFieldNames=getResultFieldNames(columns);

//

//Executequeryandbuildresultlist

//

Iteratoriter=query.iterate();

while(iter.hasNext()){

Object[]row=(Object[])iter.next();

Objectbean=beanClass.newInstance();

for(intj=0;j<row.length;j++){

if(row[j]!=null){

initialisePath(bean,attributeNames[j]);

PropertyUtils.setProperty(bean,attributeNames[j],row[j]);

}

}

results.add(bean);

}

returnresults;

}

privatestaticvoidinitialisePath(finalObjectbean,

finalStringfieldName)

throwsException{

intdot=fieldName.indexOf('.');

while(dot>=0){

StringattributeName=fieldName.substring(0,dot);

ClassattributeClass=PropertyUtils.getPropertyType(bean,attributeName);

if(PropertyUtils.getProperty(bean,attributeName)==null){

PropertyUtils.setProperty(bean,attributeName,attributeClass.newInstance());

}

dot=fieldName.indexOf('.',dot+1);

}

}

相关推荐