在hibernate使用的过程中.我们通常需要对结果进行解释.
Hibernate为我们提供了以下3种解释方法:
Transformers.ALIAS_TO_ENTITY_MAP //把输出结果转换成map
Transformers.TO_LIST //把结果按顺序排进List
ransformers.aliasToBean(target) //把结果通过setter方法注入到指定的对像属性中
在Hibernate中Transformers的所有转换都是需要实现ResultTransformer接口
详解ALIAS_TO_ENTITY_MAP ,太简单了就是把key和值直接转换到Map当中
public Object transformTuple(Object[] tuple, String[] aliases) {
Map result = new HashMap(tuple.length);
for ( int i=0; i<tuple.length; i++ ) {
String alias = aliases[i];
if ( alias!=null ) {
result.put( alias, tuple[i] );
}
}
return result;
}
详解TO_LIST,转换过程很简单,就是把value转换成List对像
public Object transformTuple(Object[] tuple, String[] aliases) {
return Arrays.asList( tuple );
}
详解aliasToBean,转换过程就是通过读取查询后的字段.然后通过使用setter方法注入到目标对像中
public AliasToBeanResultTransformer(Class resultClass) {
if ( resultClass == null ) {
throw new IllegalArgumentException( "resultClass cannot be null" );
}
this.resultClass = resultClass;
//定义属性访问器.
propertyAccessor = new ChainedPropertyAccessor(
new PropertyAccessor[] {
PropertyAccessorFactory.getPropertyAccessor( resultClass, null ),
PropertyAccessorFactory.getPropertyAccessor( "field" )
}
);
}
public Object transformTuple(Object[] tuple, String[] aliases) {
Object result;
try {
if ( setters == null ) {
setters = new Setter[aliases.length];
for ( int i = 0; i < aliases.length; i++ ) {
String alias = aliases[i];
if ( alias != null ) {
//初始指定的setter方法
setters[i] = propertyAccessor.getSetter( resultClass, alias );
}
}
}
//实例实体对像
result = resultClass.newInstance();
for ( int i = 0; i < aliases.length; i++ ) {
if ( setters[i] != null ) {
//向setter方法中指定的属性注入值
setters[i].set( result, tuple[i], null );
}
}
}
catch ( InstantiationException e ) {
throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
}
catch ( IllegalAccessException e ) {
throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
}
return result;
}
转自:
http://gznofeng.iteye.com/blog/550705