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();
}
}