hibernate原生sql查詢返回對應的實體類 調用有點麻煩 目前本身寫了2中方法 能夠記錄一下 一種hibernate提供的 須要在sql裏實現as 成實體類的類名 另外一種不須要as 直接按照駝峯式命名法 轉換。java
直接上代碼spring
hibernate的方法 Query nativeQuery = createNamedDynamicQuery(queryName, params); nativeQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(c)); List<?> objs = nativeQuery.getResultList();
本身實現的方法sql
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(); } }