1 5 package org.hibernate.transform; 6 7 import java.util.List ; 8 9 import org.hibernate.HibernateException; 10 import org.hibernate.property.ChainedPropertyAccessor; 11 import org.hibernate.property.PropertyAccessor; 12 import org.hibernate.property.PropertyAccessorFactory; 13 import org.hibernate.property.Setter; 14 15 36 public class AliasToBeanResultTransformer implements ResultTransformer { 37 38 private final Class resultClass; 39 private Setter[] setters; 40 private PropertyAccessor propertyAccessor; 41 42 public AliasToBeanResultTransformer(Class resultClass) { 43 if(resultClass==null) throw new IllegalArgumentException ("resultClass cannot be null"); 44 this.resultClass = resultClass; 45 propertyAccessor = new ChainedPropertyAccessor(new PropertyAccessor[] { PropertyAccessorFactory.getPropertyAccessor(resultClass,null), PropertyAccessorFactory.getPropertyAccessor("field")}); 46 } 47 48 public Object transformTuple(Object [] tuple, String [] aliases) { 49 Object result; 50 51 try { 52 if(setters==null) { 53 setters = new Setter[aliases.length]; 54 for (int i = 0; i < aliases.length; i++) { 55 String alias = aliases[i]; 56 if(alias != null) { 57 setters[i] = propertyAccessor.getSetter(resultClass, alias); 58 } 59 } 60 } 61 result = resultClass.newInstance(); 62 63 for (int i = 0; i < aliases.length; i++) { 64 if(setters[i]!=null) { 65 setters[i].set(result, tuple[i], null); 66 } 67 } 68 } catch (InstantiationException e) { 69 throw new HibernateException("Could not instantiate resultclass: " + resultClass.getName()); 70 } catch (IllegalAccessException e) { 71 throw new HibernateException("Could not instantiate resultclass: " + resultClass.getName()); 72 } 73 74 return result; 75 } 76 77 public List transformList(List collection) { 78 return collection; 79 } 80 81 } 82 | Popular Tags |