---
title: "Hibernate Transformers之三种结果转换说明"
author: "paynexss"
date: "2016-11-15T18:27:17Z"
tags: ["Hibernate", "封装"]
categories: ["编程语言"]
slug: "hibernate-transformers"
draft: false
lastmod: "2016-11-15T18:27:17Z"
id: 2338128
url: "https://paynexss.iteye.com/blog/2338128"
---

在hibernate使用的过程中.我们通常需要对结果进行解释.   
Hibernate为我们提供了以下3种解释方法: 

Java代码  [![收藏代码](http://lucky16.iteye.com/images/icon_star.png)]()

1. Transformers.ALIAS\_TO\_ENTITY\_MAP //把输出结果转换成map
2. Transformers.TO\_LIST //把结果按顺序排进List
3. ransformers.aliasToBean(target) //把结果通过setter方法注入到指定的对像属性中

在Hibernate中Transformers的所有转换都是需要实现ResultTransformer接口 

详解ALIAS\_TO\_ENTITY\_MAP ,太简单了就是把key和值直接转换到Map当中 

Java代码  [![收藏代码](http://lucky16.iteye.com/images/icon_star.png)]()

01. public Object transformTuple(Object\[] tuple, String\[] aliases) {
02. Map result = new HashMap(tuple.length);
03. for ( int i=0; i&lt;tuple.length; i++ ) {
04. String alias = aliases\[i];
05. if ( alias!=null ) {
06. result.put( alias, tuple\[i] );
07. }
08. }
09. return result;
10. }

详解TO\_LIST,转换过程很简单,就是把value转换成List对像 

Java代码  [![收藏代码](http://lucky16.iteye.com/images/icon_star.png)]()

1. public Object transformTuple(Object\[] tuple, String\[] aliases) {
2. return Arrays.asList( tuple );
3. }

详解aliasToBean,转换过程就是通过读取查询后的字段.然后通过使用setter方法注入到目标对像中 

Java代码  [![收藏代码](http://lucky16.iteye.com/images/icon_star.png)]()

01. public AliasToBeanResultTransformer(Class resultClass) {
02. if ( resultClass == null ) {
03. throw new IllegalArgumentException( "resultClass cannot be null" );
04. }
05. this.resultClass = resultClass;
06. //定义属性访问器.
07. propertyAccessor = new ChainedPropertyAccessor(
08. new PropertyAccessor\[] {
09. PropertyAccessorFactory.getPropertyAccessor( resultClass, null ),
10. PropertyAccessorFactory.getPropertyAccessor( "field" )
11. }
12. );
13. }
14. public Object transformTuple(Object\[] tuple, String\[] aliases) {
15. Object result;
16. try {
17. if ( setters == null ) {
18. setters = new Setter\[aliases.length];
19. for ( int i = 0; i &lt; aliases.length; i++ ) {
20. String alias = aliases\[i];
21. if ( alias != null ) {
22. //初始指定的setter方法
23. setters\[i] = propertyAccessor.getSetter( resultClass, alias );
24. }
25. }
26. }
27. //实例实体对像
28. result = resultClass.newInstance();
29. for ( int i = 0; i &lt; aliases.length; i++ ) {
30. if ( setters\[i] != null ) {
31. //向setter方法中指定的属性注入值
32. setters\[i].set( result, tuple\[i], null );
33. }
34. }
35. }
36. catch ( InstantiationException e ) {
37. throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
38. }
39. catch ( IllegalAccessException e ) {
40. throw new HibernateException( "Could not instantiate resultclass: " + resultClass.getName() );
41. }
42. return result;
43. }