hibernate select 选择列 返回bean
原文地址:
http://www.javalobby.org/articles/hibernate-query-101/
Hibernate Querying 101 : tips and tricks
查询条件
String query =
"select com.id, com.label, com.postCode, com.mayor.name
from Community as com
left join com.mayor
order by com.label ";
results = HibernateUtils.find(query);
public List find(final String hqlQuery) throws Exception {
List results = new ArrayList();
//
// Prepare a Hibernate query
//
Query query = SessionManager.currentSession().createQuery(hqlQuery);
//
// Determine the return type for this query
//
Type beanType = query.getReturnTypes()[0];
Class beanClass = beanType.getReturnedClass();
//
// Extract the list of columns returned by this query
//
String[] columns = extractColumns(hqlQuery);
//
// Pre-process bean attribute names, stripping spaces 'as' clauses
//
String[] attributeNames = getAttributeFieldNames(columns);
//
// Pre-process result field names, stripping spaces and retaining
// alias field names instead of the original column names where necessary
//
String[] resultFieldNames = getResultFieldNames(columns);
//
// Execute query and build result list
//
Iterator iter = query.iterate();
while(iter.hasNext()) {
? Object[] row = (Object[]) iter.next();
? Object bean = beanClass.newInstance();
? for (int j = 0; j < row.length; j++) {
if (row[j] != null) {
initialisePath(bean, attributeNames[j]);
PropertyUtils.setProperty(bean, attributeNames[j], row[j]);
}
? }
? results.add(bean);
}
return results;
}
private static void initialisePath(final Object bean,
?? final String fieldName)
throws Exception {
int dot = fieldName.indexOf('.');
while (dot >= 0) {
String attributeName = fieldName.substring(0, dot);
Class attributeClass = PropertyUtils.getPropertyType(bean, attributeName);
if (PropertyUtils.getProperty(bean, attributeName) == null) {
PropertyUtils.setProperty(bean, attributeName, attributeClass.newInstance());
}
dot = fieldName.indexOf('.', dot + 1);
}
}
?