码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2014-09-09 18:04:09      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   使用   java   ar   for   数据   

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属性名

标签:style   blog   color   io   使用   java   ar   for   数据   

原文地址:http://www.cnblogs.com/rigid/p/3824475.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!