zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    
    }
  • 相关阅读:
    飞鸽传书中文源码
    nohup命令参考
    Linux平台编程新手入门 C语言中的移位操作
    小技巧:让linux程序在后台运行
    2440之中断管理
    linux终端中输出彩色字体(C/SHELL)
    C语言标准中的逻辑位移和算术位移
    SQL2005利用ROW_NUMER实现分页的两种常用方式
    不用现有方法,把string转换成int型[C#]
    C# 如何生成一个时间戳
  • 原文地址:https://www.cnblogs.com/rigid/p/3824475.html
Copyright © 2011-2022 走看看