hibernate本地sql(native查询)查询的3种转换方式

在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;  
    } 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值