hibernate 原生查询实现结果集 转换成实体类

hibernate原生sql查询返回对应的实体类 调用有点麻烦 目前自己写了2中方法 可以记录一下 一种hibernate提供的  需要在sql里实现as 成实体类的类名  另一种不需要as  直接按照驼峰式命名法 转换。

直接上代码


hibernate的方法
Query nativeQuery = createNamedDynamicQuery(queryName, params);
		nativeQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(c));
		List<?> objs = nativeQuery.getResultList();

 

自己实现的方法

Query nativeQuery = createNamedDynamicQuery(queryName, params);
		nativeQuery.unwrap(SQLQuery.class).setResultTransformer(new SqlResultToBeanTransformer(c));
		return nativeQuery.getResultList();



import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import org.hibernate.HibernateException;
import org.hibernate.property.access.spi.Setter;
import org.hibernate.transform.ResultTransformer;
import org.springframework.util.StringUtils;


/**
 * Convert query result to vo list util class.
 */
public class SqlResultToBeanTransformer implements ResultTransformer {
    private static final long serialVersionUID = -5199190581393587893L;
    private final Class resultClass;
    private Setter[] setters;
    public SqlResultToBeanTransformer(Class resultClass) {
        if (resultClass == null) throw new IllegalArgumentException("resultClass cannot be null");
        this.resultClass = resultClass;
        }
    public Object transformTuple(Object[] tuple, String[] aliases) {
        Object result = null;
        try {
        	result=resultClass.newInstance();
        	
        	for (int i = 0; i < aliases.length; i++) {
                 String alias = convertColumnToProperty(aliases[i]);
                                 
                 if (alias != null && tuple[i]!=null) {
                 	mappingFieldsToObject(result,alias,tuple[i]);
                 }
             }
               
        } 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;
    }
    /**
     * Converts the specified 'XXX_YYY_ZZZ'-like column name to its
     * 'xxxYyyZzz'-like Java property name.
     *
     *   columnName the column name
     *   the Java property name
     */
    public String convertColumnToProperty(String columnName) {
        columnName = columnName.toLowerCase();
        StringBuffer buff = new StringBuffer(columnName.length());
        StringTokenizer st = new StringTokenizer(columnName, "_");
        while (st.hasMoreTokens()) {
            buff.append(StringUtils.capitalize(st.nextToken()));
        }
        buff.setCharAt(0, Character.toLowerCase(buff.charAt(0)));
        return buff.toString();
    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public List transformList(List collection) {
        return collection;
    }
    

	public void mappingFieldsToObject(Object o,String field,Object value){

        	// 从JavaBean中得到所有的方法   
        	Method[] methods = o.getClass().getDeclaredMethods();   
        	
        	Method[] superClassMethods=null;//父类方法
        	
        	//取得父类的方法
        	if(o.getClass().getGenericSuperclass()!=null){
        		Class superClass = o.getClass().getSuperclass();// 父类
        		superClassMethods=superClass.getDeclaredMethods();//父类方法
        	}
  
        	String tem1 = field;   
      
  
            if (tem1 != null && !"".equals(tem1)){   
                String methodName = "set" + tem1.substring(0, 1).toUpperCase();   
                if (tem1.length() > 1){   
                    methodName += tem1.substring(1);   
                }   
                
              //遍历方法名
                for (int i = 0; i < methods.length; i++){
                	
                    if (methodName.equals(methods[i].getName())){   
                        Method method = methods[i];   
                        
                      
                        if (method.getParameterTypes()[0] == String.class){
                        	
                        		
                            String param = null2String(value.toString());   
                            try  
                            {   
                                method.invoke(o, new Object[]{param});   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        }   
                        else if (method.getParameterTypes()[0] == int.class || method.getParameterTypes()[0]== Integer.class)   
                        {   
                            String param = null2Zero(value.toString());   
                            Integer intParam = null;   
                            try  
                            {   
                                intParam = Integer.valueOf(param);   
                            }   
                            catch (NumberFormatException e1)   
                            {   
                                intParam = new Integer(0);   
                            }   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    intParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        } 
                        else if (method.getParameterTypes()[0] == long.class || method.getParameterTypes()[0]==Long.class)   
                        {   
                            String param = null2Zero(value.toString());   
                            Long intParam = null;   
                            try  
                            {   
                                intParam = Long.valueOf(param);   
                            }   
                            catch (NumberFormatException e1)   
                            {   
                                intParam = new Long(0);   
                            }   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    intParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        } 
                        else if (method.getParameterTypes()[0] == float.class || method.getParameterTypes()[0]==Float.class)   
                        {   
                            String param = null2Zero(value.toString());   
                            Float floatParam = null;   
                            try  
                            {   
                                floatParam = Float.valueOf(param);   
                            }   
                            catch (NumberFormatException e1)   
                            {   
                                floatParam = new Float(0.0F);   
                            }   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    floatParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        }   
                        else if (method.getParameterTypes()[0] == double.class || method.getParameterTypes()[0]==Double.class)   
                        {   
                            String param = null2Zero(value.toString());   
                            Double doubleParam = null;   
                            try  
                            {   
                                doubleParam = Double.valueOf(param);   
                            }   
                            catch (NumberFormatException e1)   
                            {   
                                doubleParam = new Double(0);   
                            }   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    doubleParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        }   
                        else if (method.getParameterTypes()[0] == boolean.class || method.getParameterTypes()[0]==Boolean.class)   
                        {   
                            String param = null2String(value.toString());   
                            if (!"true".equals(param))   
                            {   
                                param = "false";   
                            }   
                            Boolean booleanParam = Boolean.valueOf(param);   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    booleanParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
                        } else if (method.getParameterTypes()[0] == Date.class)   
                        {   
//                            String param = null2String(value.toString());   
//                            Date booleanParam = CommonUtil.convertDateTime(param);
                        	
                        	Date booleanParam = (Date) value;
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    booleanParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
                        } else if (method.getParameterTypes()[0] == BigDecimal.class)   
                        {   
                      	
                        	BigDecimal bigDecimalParam = (BigDecimal) value;
                          try  
                          {   
                              method.invoke(o, new Object[]   
                              {   
                            		  bigDecimalParam   
                              });   
                          }   
                          catch (Exception e)   
                          {   
                              e.printStackTrace();   
                              System.out.println("注入值时出错");   
                          }   
                      } else if (method.getParameterTypes()[0] == char.class || method.getParameterTypes()[0] == Character.class)   
                      {    
                    	  Character characterParam = (Character)value;     
                          try  
                          {   
                              method.invoke(o, new Object[]   
                              {   
                            		characterParam   
                              });   
                          }   
                          catch (Exception e)   
                          {   
                              e.printStackTrace();   
                              System.out.println("注入值时出错");   
                          }
                    }  
                        break;   
                    }   
  
                }
                
                
              //遍历父类方法名
                for (int i = 0; i < superClassMethods.length; i++){
                	
                    if (methodName.equals(superClassMethods[i].getName())){   
                        Method method = superClassMethods[i];   
                        
                    
                       
                        if (method.getParameterTypes()[0] == String.class){   
                            String param = null2String(value.toString());   
                            try  
                            {   
                                method.invoke(o, new Object[]{param});   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        }   
                        else if (method.getParameterTypes()[0] == int.class || method.getParameterTypes()[0]== Integer.class)   
                        {   
                            String param = null2Zero(value.toString());   
                            Integer intParam = null;   
                            try  
                            {   
                                intParam = Integer.valueOf(param);   
                            }   
                            catch (NumberFormatException e1)   
                            {   
                                intParam = new Integer(0);   
                            }   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    intParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        } 
                        else if (method.getParameterTypes()[0] == long.class || method.getParameterTypes()[0]==Long.class)   
                        {   
                            String param = null2Zero(value.toString());   
                            Long intParam = null;   
                            try  
                            {   
                                intParam = Long.valueOf(param);   
                            }   
                            catch (NumberFormatException e1)   
                            {   
                                intParam = new Long(0);   
                            }   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    intParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        } 
                        else if (method.getParameterTypes()[0] == float.class || method.getParameterTypes()[0]==Float.class)   
                        {   
                            String param = null2Zero(value.toString());   
                            Float floatParam = null;   
                            try  
                            {   
                                floatParam = Float.valueOf(param);   
                            }   
                            catch (NumberFormatException e1)   
                            {   
                                floatParam = new Float(0.0F);   
                            }   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    floatParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        }   
                        else if (method.getParameterTypes()[0] == double.class || method.getParameterTypes()[0]==Double.class)   
                        {   
                            String param = null2Zero(value.toString());   
                            Double doubleParam = null;   
                            try  
                            {   
                                doubleParam = Double.valueOf(param);   
                            }   
                            catch (NumberFormatException e1)   
                            {   
                                doubleParam = new Double(0);   
                            }   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    doubleParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
  
                        }   
                        else if (method.getParameterTypes()[0] == boolean.class || method.getParameterTypes()[0]==Boolean.class)   
                        {   
                            String param = null2String(value.toString());   
                            if (!"true".equals(param))   
                            {   
                                param = "false";   
                            }   
                            Boolean booleanParam = Boolean.valueOf(param);   
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    booleanParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
                        } else if (method.getParameterTypes()[0] == Date.class)   
                        {   
//                            String param = null2String(value);   
                           
//                            Date booleanParam = CommonUtil.convertDateTime(param);
                        	Date booleanParam = (Date) value;
                            try  
                            {   
                                method.invoke(o, new Object[]   
                                {   
                                    booleanParam   
                                });   
                            }   
                            catch (Exception e)   
                            {   
                                e.printStackTrace();   
                                System.out.println("注入值时出错");   
                            }   
                        } else if (method.getParameterTypes()[0] == BigDecimal.class)   
                        {   
                      	
                        	BigDecimal bigDecimalParam = (BigDecimal) value;
                          try  
                          {   
                              method.invoke(o, new Object[]   
                              {   
                            		  bigDecimalParam   
                              });   
                          }   
                          catch (Exception e)   
                          {   
                              e.printStackTrace();   
                              System.out.println("注入值时出错");   
                          }   
                      } else if (method.getParameterTypes()[0] == char.class || method.getParameterTypes()[0] == Character.class)   
                      {    
                    	  Character characterParam = (Character)value;     
                          try  
                          {   
                              method.invoke(o, new Object[]   
                              {   
                            		characterParam   
                              });   
                          }   
                          catch (Exception e)   
                          {   
                              e.printStackTrace();   
                              System.out.println("注入值时出错");   
                          }
                    }    
                        break;   
                    }   
  
                }
            }   
  
        
        
}
	
	

    private static String null2Zero(String str)   
    {   
        if (str == null || "".equals(str.trim()))   
        {   
            return "0";   
        }   
        return str.trim();   
    }   
  
    private static String null2String(String str)   
    {   
        if (str == null)   
        {   
            return "";   
        }   
        return str.trim();   
    }   
}

 

转载于:https://my.oschina.net/u/3065626/blog/1813095

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值