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

}
时间: 2025-01-05 22:03:55

hibernate 数据库列别名自动映射pojo属性名的相关文章

Hibernate (开源对象关系映射框架)

一.基本介绍1.它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm(对象关系映射)框架,hibernate可以自动生成SQL语句,自动执行: Hibernate可以应用在任何使用JDBC的场合. 2.持久化层:处理关系型数据库(数据存储层)和模型对象(object,业务逻辑模型)的映射关系的代码方法(ORM)3.Hibernate是一个基于JDBC的主流持久化框架,对JDBC访问数据库的代码做了封装,大大简化了数据访问层繁琐的重复性代码,是一个优秀的

springboot(7)配置文件自动映射

SpringBoot注解配置文件自动映射到属性和实体类 Controller上面配置 @Component @PropertySource({"classpath:application.properties"}) @ConfigurationProperties 属性上面配置 @Value("${test.name}") 原文地址:https://www.cnblogs.com/xeclass/p/12635245.html

反射+自定义注解---实现Excel数据列属性和JavaBean属性的自动映射

简单粗暴,直奔主题.   需求:通过自定义注解和反射技术,将Excel文件中的数据自动映射到pojo类中,最终返回一个List<pojo>集合? 今天我只是通过一位使用者的身份来给各位分享一套超级可以的POI"工具",这套工具我只是第一个使用者,创作者是我的朋友,他喜好钻研底层和算法,擅长计算机软硬件,在我心里他一直是神一样的存在,每天晚上10点后我才能看到他,因为他每天需要加班,需要有更多时间能够学习,唉,这种毅力和耐力,我是真的羡慕,因为我也一直在努力,能够得到更多的东

在MyEclipse的web项目/java项目中,使用Hibernate-tools中的hbm2java和hbm2ddl工具,根据hbm文件自动生成pojo和数据库脚本

     首先,我一定要吐槽下,这个Ant管理部署项目的工具,以及hibernate刚刚学习,导入我这一个简单的问题整了一天多,实在效率有点低下.在这两天中,①了解了Ant,知道了在Ant中很灵活的步骤项目的情况,知道了build.xml文件的一些基本写法.②还学习了在MyEclipse这样的集成工具中完成项目部署.③以及在这两种情况中,利用hibernateTools中的hbm2java和hbm2ddl工具,根据对象关系映射文件,自动生成POJO以及SQL文件(就是数据表). 一,在web项目

(转)Hibernate框架基础——映射集合属性

http://blog.csdn.net/yerenyuan_pku/article/details/52745486 集合映射 集合属性大致有两种: 单纯的集合属性,如像List.Set或数组等集合属性. Map结构的集合属性,每个属性值都有对应的Key映射. 集合映射的元素大致有如下几种: list:用于映射List集合属性. set:用于映射Set集合属性. map:用于映射Map集合性. array:用于映射数组集合属性. bag:用于映射无序集合. idbag:用于映射无序集合,但为集

浅谈Hibernate中映射集合属性以及主键和外键

首先说明一下什么叫主键以及外键. 主键和外键是对于数据库来说的,数据库的表才有主键外键的说法. 主键:主键是指标识某个表中唯一且非空的一条记录行的列,这个列中的值不允许有重复的值,用于确定一个表中的一条记录,实际上主键就是告诉别人:这个数据列是唯一的. 外键:引用另外一个表中的主键,在当前表中不一定为唯一的,但是在被引用表中一般唯一.对于关系型数据库来说(比如MySQL)外键是联系数据表之间的唯一方式,主要目的是控制存储在外键表中的数据. 建立外键的前提:本表的列必须与外键类型相同(外键必须是外

hibernate映射集合属性

注意:持久化集合字段必须声明为接口,两个持久化对象不能共享同一个集合元素的引用. 映射集合属性 @ElementCollection{ fetch targetClass } 映射集合属性表 @CollectionTable{ name catalog schema indexes joinColumns uniqueConstraints } @JoinColumn{ columnDefinition name insertable updatable nullable table uniqu

Maven项目中,使用mybatis,根据数据库自动生成pojo实体类、dao、mapper

一.首先,用eclipse创建一个maven项目. 二.其次,在pom.xml文件下,加入如下插件配置: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.ap

阿里规范 - 五、MySQL 数据库 - (四)ORM映射 - 3 - 【强制】不要用 resultClass 当返回参数,即使所有类属性名与数据库字段一一对应

Batis的返回值参数类型有:resultMap与resultClass 一.当结果集列名和类的属性名完全相对应的时候,则可直接用resultClass直接指定查询结果类型. 二.当查询结果集与属性名对应不上时,可以采用resultMap指定列名与对象属性名之间的对应关系,否则对应不上的属性将为null或0. 不要用  resultClass   用  resultMap 原文地址:https://www.cnblogs.com/light-train-union/p/12228734.html