Over and over again I notive myself getting a list from hibernate, and the first thing next is put it in an idmap
like:
List<House> entities = s.createCriteria(House.class).list();
Map<String,House> entitymap = new Has开发者_运维问答hMap<String,House>();
for(TA_entity e:entities){
entitymap.put(e.getId(), e);
}
Is there a way to get this directly out of hibenerate? afterall Hibernate is familiar with the id.
There isn't anything out of the box, but extending CriteriaImpl shouldn't be too difficult. Something like:
public class MapCriteria extends CriteriaImpl implements Criteria {
public MapCriteria( Criteria criteria ) {
super( ((CriteriaImpl)criteria).getEntityOrClassName(), ((CriteriaImpl)criteria).getSession() );
}
public <I, T> Map<I, T> map( String indexMethodName ) throws HibernateException {
Map<I, T> map = null;
try {
List<T> results = list();
if ( null != results ) {
map = new HashMap<I, T>();
if ( !results.isEmpty() ) {
Class clazz = Class.forName( getEntityOrClassName() );
Class[] params = new Class[0];
Method method = clazz.getMethod( indexMethodName, params );
Object[] args = new Object[0];
for ( T result : results ) {
I index = (I) method.invoke( result, args );
map.put( index, result );
}
}
}
}
catch (ClassNotFoundException e) {
throw new HibernateException( e );
}
catch (NoSuchMethodException e) {
throw new HibernateException( e );
}
catch (IllegalArgumentException e) {
throw new HibernateException( e );
}
catch (IllegalAccessException e) {
throw new HibernateException( e );
}
catch (InvocationTargetException e) {
throw new HibernateException( e );
}
return (Map<I, T>) map;
}
}
Then you should be able to call
Map<String, House> entitymap = new MapCriteria(s.createCriteria(House.class).list()).<String, House>map("getId");
This should save you from having to code the conversion to map each time.
精彩评论