首页 > 代码库 > hibernate 数据库列别名自动映射pojo属性名

hibernate 数据库列别名自动映射pojo属性名

package com.pccw.business.fcm.common.hibernate;import java.lang.reflect.Field;import java.math.BigDecimal;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.property.ChainedPropertyAccessor;import org.hibernate.property.PropertyAccessor;import org.hibernate.property.PropertyAccessorFactory;import org.hibernate.property.Setter;import org.hibernate.transform.ResultTransformer;/** * 自定义的数据库字库转换成POJO */public class ExtColumnToBean implements ResultTransformer {    private static final long serialVersionUID = 1L;    private final Class resultClass;    private Setter[] setters;    private PropertyAccessor propertyAccessor;    private List<Field> fields = new ArrayList<Field>();    BigDecimal bigDecimal = null;    public ExtColumnToBean(Class resultClass) {        if (resultClass == null)            throw new IllegalArgumentException("resultClass cannot be null");        this.resultClass = resultClass;        propertyAccessor = new ChainedPropertyAccessor(new PropertyAccessor[] {                PropertyAccessorFactory.getPropertyAccessor(resultClass, null),                PropertyAccessorFactory.getPropertyAccessor("field") });    }    // 结果转换时,HIBERNATE调用此方法    public Object transformTuple(Object[] tuple, String[] aliases) {        Object result;        try {            if (setters == null) {// 取得目标POJO类的所有SETTER方法                setters = new Setter[aliases.length];                for (int i = 0; i < aliases.length; i++) {                    String alias = aliases[i];                    if (alias != null) {                        setters[i] = getSetterByColumnName(alias);                    }                }            }            result = resultClass.newInstance();            // 这里使用SETTER方法填充POJO对象            for (int i = 0; i < aliases.length; i++) {                if (setters[i] != null) {                    Class[] parameterTypes = setters[i].getMethod().getParameterTypes();                    if(parameterTypes == null || parameterTypes.length == 0){                        continue;                    }                    //pojo set方法默认只有一个参数                    if(parameterTypes[0].equals(Integer.class)){                        if(tuple[i] instanceof BigDecimal){                            bigDecimal = (BigDecimal)tuple[i];                            setters[i].set(result, bigDecimal.intValue(), null);                        }                    }else if(parameterTypes[0].equals(Long.class)){                        if(tuple[i] instanceof BigDecimal){                            bigDecimal = (BigDecimal)tuple[i];                            setters[i].set(result, bigDecimal.longValue(), null);                        }                    }else if(parameterTypes[0].equals(Double.class)){                        if(tuple[i] instanceof BigDecimal){                            bigDecimal = (BigDecimal)tuple[i];                            setters[i].set(result, bigDecimal.doubleValue(), null);                        }                    }else{                        setters[i].set(result, tuple[i], null);                    }                }            }        } 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;    }    /**     * 根据数据库字段名在POJO查找JAVA属性名 如:USER_ID 如果没有对应的属性名返回null     *      * @param alias     *            数据库字段名     * @return     */    private Setter getSetterByColumnName(String alias) {        // 取得POJO所有属性名        // Field[] fields = resultClass.getDeclaredFields();        if (fields.isEmpty()) {            this.getClassField(resultClass);        }        if (fields == null || fields.size() == 0) {            throw new RuntimeException("实体" + resultClass.getName() + "不含任何属性");        }        // 把字段名中所有的下杠去除        String proName = alias.replaceAll("_", "").toLowerCase();        for (int i = 0; i < fields.size(); i++) {            Field field = fields.get(i);            //System.out.println(field.getName().toLowerCase());            if (field.getName().toLowerCase().equals(proName)) {// 去除下杠的字段名如果和属性名对得上,就取这个SETTER方法                return propertyAccessor.getSetter(resultClass, field.getName());            }        }        return null;    }    @SuppressWarnings("unchecked")    public List transformList(List collection) {        return collection;    }    private void getClassField(Class c) {        Field[] fs = c.getDeclaredFields();        if (fs != null && fs.length > 0) {            List li = Arrays.asList(fs);            fields.addAll(li);        }        Class superclass = c.getSuperclass();        if (superclass != null) {// 简单的递归一下            getClassField(superclass);        }    }}

 

hibernate 数据库列别名自动映射pojo属性名