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

}

hibernate 反射框架(自用),布布扣,bubuko.com

时间: 2024-11-05 13:39:41

hibernate 反射框架(自用)的相关文章

Struts2+Hibernate+Spring框架实现增删改查

一.添加3个框架的JAR包,完成后写配置文件: 1.web配置文件: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation=&quo

JAVAWEB开发之Hibernate详解(一)——Hibernate的框架概述、开发流程、CURD操作和核心配置与API以及Hibernate日志的使用

Hibernate框架概述 什么是Hibernate? 框架:软件的半成品,完成部分代码的功能. Hibernate:Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思想来操作数据库.Hibernate可以应用在任何使用JDBC的场合,既可以在Java的客户端程序中使用,也可以在Servlet/JSP的web应用程序中使用,最具革命意义的是,Hibernate可以在应用EJB的J2EE架构中取代CMP,完成

Struts,spring,hibernate三大框架的面试

Struts,spring,hibernate三大框架的面试 1.Hibernate工作原理及为什么要用? 原理: 1.读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3.打开Session 4.创建事务Transation 5.持久化操作 6.提交事务 7.关闭Session 8.关闭SesstionFactory  为什么要用: 1. 对JDBC访问数据库的代码做了封装,大大简化了数据访问层繁琐的重复性代码. 2. Hibernate是一个基于JDBC的主流持久

Struts,Spring,Hibernate三大框架 面试题

Struts,Spring,Hibernate三大框架 1.Hibernate工作原理及为什么要用? 原理: 1.读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3.打开Session 4.创建事务Transation 5.持久化操作 6.提交事务 7.关闭Session 8.关闭SesstionFactory 为什么要用: 1. 对JDBC访问数据库的代码做了封装,大大简化了数据访问层繁琐的重复性代码. 2. Hibernate是一个基于JDBC的主流持久化框架,

Struts2+Spring+Hibernate 三大框架的合并集成

这次来看看Struts2+Spring+Hibernate三大框架的整合应用,主要是Spring和Hibernate框架的整合,因为前边已经将Strtus2+Spring整合过了基本一样.  首先看一下分工吧: Struts2做的MVC的流程框架,主要完成从客户端访问到选择action的过程,其中过滤器起到了Controller的作用,action属于model,而jsp则是view页面的展示. Spring主要利用Ioc的特长来管理各种对象:action,service,dao,数据访问源,H

Hibernate+Struts2框架设计

Hibernate+Struts2框架设计

hibernate 单元测试框架

hibernate在写数据库配置文件时非常的不确定,必须进行必要的测试保证数据库结构的正确性.所以可以应用junit进行测试. 使用junit非常简单,eclipse只需要右键项目新建一个junit test case即可(填写类名和包名).然后在对应位置写对应的代码运行测试即可. 下面给出一个常用的hibernate测试框架: package com.atguigu.hibernate.entities; import java.io.FileInputStream; import java.

swift反射框架及扩展框架

反射框架:https://github.com/evermeer/EVReflection 扩展框架(用于json与对象之间的转换):https://github.com/evermeer/AlamofireJsonToObjects

Eclipse搭建SSH(Struts2+Spring+Hibernate)框架教程

| 版权声明:本文为博主原创文章,未经博主允许不得转载. 前言 确实,刚创博客,对于这个陌生的东西还是有些许淡然.这是我的第一篇博文,希望能给你们有帮助,这就是我最大的乐趣! 好了下面进入正题: SSH框架简介:①SSH框架是由struts2.spring.hibernate三大框架组合起来的一套总框架,一般来说这三个东西我们不会单独使用.  ②在学习SSH框架之前建议读者先学mvc,因为SSH是在mvc基础上根据mvc的缺点而产生的一套比较成熟的框架,也比较稳定.  ③SSH框架的流程:浏览器