hibernate 反射框架(自用)

hibernate 只需要操作对象就可以对数据库的数据进行“增删改查”。用了短时间后,感觉依旧存在很大的冗余。正因为这个,我的反射框架就出现了。因为自用,下面只贴出代码,不做解释。有兴趣的可以来看看一起研究一下,如有问题可私聊探讨。

反射基类      SQLSuper

/**
 * 给对象做反射并且定于返回HQL语句方法的抽象类
 * @author vincent Mao
 *
 */
public abstract class SQLSuper {
    /**
     * 
     */
    protected StringBuffer SQL;

    public StringBuffer getSQL() {
        return SQL;
    }

    public void setSQL(StringBuffer sQL) {
        SQL = sQL;
    }
    /**
     * 根据传入的实体对象and条件集合and排序对象返回HQL语句
     * @param obj 经过重新封装的实体类
     * @param condition 条件集合
     * @param orderBy 排序对象
     * @return HQL
     */
    public abstract String getSQL(Object obj , List condition,OrderBy orderBy);
    
    /**
     * 返回所有类的名字
     * @param tables
     * @return List<String>
     */
    protected List<String> getClassNames(List<?> tables){
        List<String> classNames = null;
        if(tables != null && tables.size()!=0){
            classNames = new ArrayList<String>();
            for(Object obj : tables){
                classNames.add(obj.getClass().getSimpleName());
            }
        }
        return classNames;
    }
    
    /**
     * 返回类的名字
     * @param table
     * @return
     */
    protected String getClassName(Object table){
        String className = null;
        if(table != null){
            className=table.getClass().getSimpleName();
        }
        return className;
    }
    
    /**
     * 给传入的对象做反射
     * @param o
     * @return 
     */
    protected Class<?> getClassReverberate(Object o){
        String ClassName = o.getClass().getName();
        Class<?> demo = null;
        try {
            demo = Class.forName(ClassName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return demo;
    }
    
    /**
     * 返回类中的所有属性
     * @param o
     * @return List<String>
     */
    public List<String> getClassPropertyName(Object o) {
        Class<?> demo = this.getClassReverberate(o);
        List<String> classPropertyNames = null;
        Field[] field = demo.getDeclaredFields();
        classPropertyNames = new ArrayList<String>();
        for (int i = 0; i < field.length; i++) {
            classPropertyNames.add(field[i].getName());
        }
        return classPropertyNames;
    }
    
    /**
     * 返回类中所有属性数据类型
     * @param c
     * @return
     */
    public List<Class<?>> getClassPropertyType(Class<?> c){
        List<Class<?>> classPropertyTypes = null;
        Field[] field = c.getDeclaredFields();
        classPropertyTypes = new ArrayList<Class<?>>();
        for (int i = 0; i < field.length; i++) {
            classPropertyTypes.add(field[i].getType());
        }
        return classPropertyTypes;
    }
    
    /**
     * 返回类中的所有属性和属性数据类型
     * @param c
     * @return
     */
    public Map<String, Class<?>> getClassPropertyNameAndType(Class<?> c){
        Map<String, Class<?>> classPropertyNamesAndTypes = null;
        Field[] field = c.getDeclaredFields();
        classPropertyNamesAndTypes = new HashMap<String, Class<?>>();
        for (int i = 0; i < field.length; i++) {
            classPropertyNamesAndTypes.put(field[i].getName(),field[i].getType());
        }
        return classPropertyNamesAndTypes;
    }
    
    /**
     * 使用反射调用对象的get方法
     * @param obj
     *            操作的对象
     * @param att
     *            操作的属性
     * */
    public Object getter(Object obj, String att) {
        try {
            Method method = obj.getClass().getMethod("get" + firstLower(att));
            return method.invoke(obj);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 使用反射调用对象的set方法
     * @param obj
     *            操作的对象
     * @param att
     *            操作的属性
     * @param value
     *            设置的值
     * @param type
     *            参数的属性
     * */
    public void setter(Object obj, String att, Object value,
            Class<?> type) {
        try {
            Method method = obj.getClass().getMethod("set" + firstLower(att), type);
            method.invoke(obj, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 给setter()的操作的属性首字母大写
     * @param att setter()操作的属性
     * @return 
     */
    protected String firstLower(String att) {
        StringBuffer sb = new StringBuffer();
        sb.append(att.substring(0,1).toUpperCase());
        sb.append(att.substring(1, att.length()));
        return sb.toString();
    }
}

反射使用类 SQLUtil

/**
 * 返回HQL语句的工具类,实现SQLSuper抽象类
 * @author vincent Mao
 *
 */
public class SQLUtil extends SQLSuper {
    
    /**
     * 根据传入实体,条件集合,排序实体生成对应的HQL
     */
    public String getSQL(Object detachedObject , List condition ,OrderBy orderBy) {
        /*if(condition == null){
            condition = new ArrayList();
        }*/
        StringBuffer sb = new StringBuffer();
        sb.append(" from ");
        sb.append(this.getClassName(detachedObject));
        //sb.append(" where ");
        StringBuffer conditionSQL = new StringBuffer();
        List<String> classPropertyNames = this.getClassPropertyName(detachedObject);
        for (String classPropertyName : classPropertyNames) {
            Object detachedObjectPropertyValue = this.getter(detachedObject, classPropertyName.toString());
            if (detachedObjectPropertyValue == null || detachedObjectPropertyValue.equals("-1") || detachedObjectPropertyValue.toString().equals("-1")) {
                continue;
            }
            /*if (i > 0) {
                conditionSQL.append(" and ");
            }*/
            if(detachedObjectPropertyValue instanceof List){
                //Object[] array = (Object[])detachedObjectPropertyValue;
                //Array array = (Array) detachedObjectPropertyValue;
                List array = (List) detachedObjectPropertyValue;
                if(array.size()==1){
                    conditionSQL.append(classPropertyName.replace('_', '.')+" > ?");
                    condition.add(array.get(0));
                }else if(array.size()==2){
                    conditionSQL.append(classPropertyName.replace('_', '.')+" between ? and ?");
                    condition.add(array.get(0));
                    condition.add(array.get(1));
                }
            }else if(detachedObjectPropertyValue instanceof Set){
                continue;
            }else{
                SQLWhereEntity whereEntity = new SQLWhereEntity();
                String whereEntityHQL = whereEntity.matchingEntity(detachedObjectPropertyValue,condition);                
                if(whereEntityHQL!=null){
                    conditionSQL.append(classPropertyName.replace('_', '.')+" in "+"("+whereEntityHQL+")");
                }else{
                    conditionSQL.append(classPropertyName.replace('_', '.')+" = ? ");
                    condition.add(detachedObjectPropertyValue);
                }
            }
            conditionSQL.append(" and ");
            
        }
        if(conditionSQL.toString().length()>0){
            sb.append(" where ");
            sb.append(conditionSQL.toString());
            sb.delete(sb.lastIndexOf("and"), sb.length());
        }
        if(orderBy!=null){
            sb.append(" order by ");
            sb.append(orderBy.getColumn());
            sb.append("  ");
            sb.append(orderBy.getType());
        }
        System.out.println(sb.toString());
        for (Object o : condition) {
            System.out.println(o);
        }
        return sb.toString();
    }
    
    /**
     * 返回准备update的对象
     * 操作非null的字段,八大基本数据类型加上String和Byte如果为相同则continue
     * @param detachedObject
     * @param persistentObject
     * @return
     */
    public Object getUpdateObject(Object detachedObject,Object persistentObject){
        if(detachedObject == persistentObject){
            return detachedObject;
        }
        detachedObject = this.getAddObject(detachedObject);
        //Object persistentObject = this.get((Serializable) this.getter(detachedObject, "uuid"));
        List<String> classPropertyNames = this.getClassPropertyName(detachedObject);
        for(String classPropertyName : classPropertyNames){
            Object detachedObjectPropertyValue = this.getter(detachedObject, classPropertyName);
            if (detachedObjectPropertyValue == null || detachedObjectPropertyValue.equals("-1") || detachedObjectPropertyValue.toString().equals("-1")) {
                continue;
            }
            if(detachedObjectPropertyValue instanceof List){
                continue;
            }else if(detachedObjectPropertyValue instanceof Set){
                Object persistentObjectPropertyValue = this.getter(persistentObject, classPropertyName);
                for(Object obj : (Set)detachedObjectPropertyValue){
                    ((Set)persistentObjectPropertyValue).add(obj);
                }
                continue;
            }else{
                Object persistentObjectPropertyValue = this.getter(persistentObject, classPropertyName);
                if(persistentObjectPropertyValue!=null){
                    if(persistentObjectPropertyValue instanceof Object){
                        if(persistentObjectPropertyValue instanceof Integer){
                            if(Integer.parseInt(persistentObjectPropertyValue.toString()) == Integer.parseInt(detachedObjectPropertyValue.toString())){
                                continue;
                            }
                        }else if(persistentObjectPropertyValue instanceof String){
                            if(persistentObjectPropertyValue.toString().trim().equals(detachedObjectPropertyValue.toString().trim())){
                                continue;
                            }
                        }else if(persistentObjectPropertyValue instanceof Double){
                            if(Double.parseDouble(persistentObjectPropertyValue.toString()) == Double.parseDouble(detachedObjectPropertyValue.toString())){
                                continue;
                            }
                        }else if(persistentObjectPropertyValue instanceof Date){
                            if(((Date)persistentObjectPropertyValue)== (Date)detachedObjectPropertyValue){
                                continue;
                            }
                        }else if(persistentObjectPropertyValue instanceof Short){
                            if((Short.parseShort(persistentObjectPropertyValue.toString()))== Short.parseShort(detachedObjectPropertyValue.toString())){
                                continue;
                            }
                        }else if(persistentObjectPropertyValue instanceof Boolean){
                            
                            if((Boolean.parseBoolean(persistentObjectPropertyValue.toString()))== Boolean.parseBoolean(detachedObjectPropertyValue.toString())){
                                continue;
                            }
                        }else if(persistentObjectPropertyValue instanceof Byte){
                            if((Byte.parseByte(persistentObjectPropertyValue.toString()))== Byte.parseByte(detachedObjectPropertyValue.toString())){
                                continue;
                            }
                        }else if(persistentObjectPropertyValue instanceof Long){
                            if((Long.parseLong(persistentObjectPropertyValue.toString()))== Long.parseLong(detachedObjectPropertyValue.toString())){
                                continue;
                            }
                        }else if(persistentObjectPropertyValue instanceof Float){
                            if((Float.parseFloat(persistentObjectPropertyValue.toString()))== Float.parseFloat(detachedObjectPropertyValue.toString())){
                                continue;
                            }
                        }else if(persistentObjectPropertyValue instanceof Character){
                            if((Character)persistentObjectPropertyValue== (Character)detachedObjectPropertyValue){
                                continue;
                            }
                        }else{
                            
                        }
                        /*else if(persistentObjectPropertyValue instanceof Serializable){                        
                        }*/
                    }
                }
                System.out.println(classPropertyName+"&&"+detachedObjectPropertyValue.toString().trim()+"&&"+detachedObjectPropertyValue.getClass());
                this.setter(persistentObject, classPropertyName, detachedObjectPropertyValue, detachedObjectPropertyValue.getClass());
            }
        }
        return persistentObject;
    }
    
    /**
     * json-lib用,返回不需要生成json的字段
     * @param detachedObjectClass 类
     * @param level 级别通常为2级
     * @return
     */
    public List<String> getIgnoreObjectName(Class<?> detachedObjectClass,int level){
        int levelCount = 1;
        List<String> ignoreObjectNames = new ArrayList<String>();
        if(detachedObjectClass!=null){
            Map<String,Class<?>> classPropertyNamesAndTypes = this.getClassPropertyNameAndType(detachedObjectClass);
            for(String classPropertyName : classPropertyNamesAndTypes.keySet()){
                if(classPropertyNamesAndTypes.get(classPropertyName) == Integer.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == Double.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == Date.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == Short.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == Boolean.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == Byte.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == Long.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == Float.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == Character.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == List.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == String.class){
                    continue;
                }else if(classPropertyNamesAndTypes.get(classPropertyName) == Set.class){
                    //ignoreObjectNames.add(classPropertyName);
                    //System.out.println("过滤"+classPropertyName+"----Set集合");
                }else{
                    if(levelCount < level){
                        ignoreObjectNames.addAll(getIgnoreObjectName(classPropertyNamesAndTypes.get(classPropertyName) ,level-levelCount));
                    }else{
                        ignoreObjectNames.add(classPropertyName);
                        //System.out.println("过滤"+classPropertyName+"----"+classPropertyNamesAndTypes.get(classPropertyName)+"对象");
                    }
                }
            }
        }
        return ignoreObjectNames;
    }
    
    /**
     * json-lib用,返回不需要生成json的字段(忽略Object和Set)
     * @param detachedObject 传入需要转换json的对象
     * @return
     */
    public List<String> getIgnoreObjectName(Object detachedObject){
        List<String> ignoreObjectNames = new ArrayList<String>();
        if(detachedObject!=null){
            List<String> classPropertyNames = this.getClassPropertyName(detachedObject);
            for(String classPropertyName : classPropertyNames){
                Object detachedObjectPropertyValue = this.getter(detachedObject, classPropertyName);
                if(detachedObjectPropertyValue!=null){
                    if(detachedObjectPropertyValue instanceof Object){
                        if(detachedObjectPropertyValue instanceof Integer){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof String){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Double){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Date){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Short){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Boolean){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Byte){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Long){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Float){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Character){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof List){
                            continue;
                        }else{
                            ignoreObjectNames.add(classPropertyName);
                        }
                    }
                }
            }
        }
        return ignoreObjectNames;
    }
    
    /**
     * 返回
     * @param detachedObject
     * @return
     */
    public Object getAddObject(Object detachedObject){
        List<String> classPropertyNames = this.getClassPropertyName(detachedObject);
        for(String classPropertyName : classPropertyNames){
            Object detachedObjectPropertyValue = this.getter(detachedObject, classPropertyName);
            if (detachedObjectPropertyValue == null || detachedObjectPropertyValue.equals("-1") || detachedObjectPropertyValue.toString().equals("-1")) {
                continue;
            }
            if(detachedObjectPropertyValue instanceof List){
                continue;
            }else if(detachedObjectPropertyValue instanceof Set){
                continue;
            }else{
                if(detachedObjectPropertyValue!=null){
                    if(detachedObjectPropertyValue instanceof Object){
                        if(detachedObjectPropertyValue instanceof Integer){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof String){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Double){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Date){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Short){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Boolean){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Byte){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Long){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Float){
                            continue;
                        }else if(detachedObjectPropertyValue instanceof Character){
                            continue;
                        }else{
                            try {
                                if(this.getter(detachedObjectPropertyValue, "uuid")!=null){
                                    continue;
                                }
                            } catch (Exception e) {
                                continue;
                            }
                        }
                    }
                    System.out.println(classPropertyName+"&&"+detachedObjectPropertyValue.toString().trim()+"&&"+detachedObjectPropertyValue.getClass());
                    this.setter(detachedObject, classPropertyName, null, detachedObjectPropertyValue.getClass());
                }
            }
        }
        return detachedObject;
    }
    
    /*public static void main(String[] args) {
        House house = new House();
        house.setId(2);
        house.setStreet_id(3);
        SQLUtil sql = new SQLUtil();
        System.out.println(sql.getSQL(house));
    }*/
    
    /**
     * 返回查询记录数的HQL
     * @param obj    需要查询的表的实体
     * @param sql : from....where.......
     * @return
     */
    public String getRowCountSQL(Object obj , String sql) {
        StringBuffer sb = new StringBuffer();
        List<String> classPropertyName = this.getClassPropertyName(obj);
        sb.append(" select Count(");
        sb.append(classPropertyName.get(0));
        sb.append(") ");
        sb.append(sql);
        System.out.println(sb.toString());
        return sb.toString();
    }
    

}
原文地址:https://www.cnblogs.com/BrightMoon/p/3830385.html