⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 activerecordhelper.java

📁 一个Java持久层类库
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package ActiveObject.core;import ActiveObject.common.Flag;import ActiveObject.exception.ObjectAnalysisException;import ActiveObject.po.Role;import ActiveObject.vo.*;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Modifier;import java.sql.*;import java.util.*;/** * @author tanjiazhang */public class ActiveRecordHelper {    //表名到对象信息的映射    static Map<String, ObjectInfo> activeLibrary = new HashMap();         /**     * 公共的更新方法,方便以后统一修改     * @param sql     * @param params     * @throws java.sql.SQLException     */    static int excuteUpdate (String sql, Object... params) throws java.sql.SQLException {        Connection connection = ActiveRecord.getConnection();        PreparedStatement stmt = connection.prepareStatement(sql);        int index = 1;//System.err.println(sql+" "+params.length);        for(Object item : params)        {            stmt.setObject(index++, item);        }        index = stmt.executeUpdate();        stmt.close();        connection.close();        return index;    }    static ResultReader excuteQuery(String sql, Object... params) throws java.sql.SQLException    {        return new ResultReader(sql, params);    }//    static Map<Field, Accesstor> analizeObjectFields_deleted(ActiveRecord object)//    {//        ObjectInfo objs = ActiveRecord.objectInformationBase.get(object.getClass().getName());//        Map<Field, Accesstor> objects = null;//        if(objs != null)//            objects = objs.getFieldAccesstorMapping();//        if(objects != null)//            return objects;////        //如果该持久化类的信息未被缓存,则开始分析//        objects = new HashMap<Field, Accesstor>();//        Class currentClass = object.getClass();////        /**开始读取所有符合规范的字段//         * 命名符合JavaBean的命名规范,存取器声明为公开//         *///        while(currentClass != null)//        {//            for(Field field : currentClass.getDeclaredFields())//            {//                if(field.getName().equals("id"))//                    continue;//                try//                {//                    Method getter = currentClass.getMethod(ActiveRecordHelper.getGetterNameByField(field.getName()));//                    Method setter = currentClass.getMethod(ActiveRecordHelper.getSetterNameByField(field.getName()), field.getType());//                    if(getter.getModifiers() == Modifier.PUBLIC && setter.getModifiers() == Modifier.PUBLIC)//                        objects.put(field, new Accesstor(getter, setter));//                }//                catch(Exception err)//                {//                    //It means that it's not a valid field//                }//            }//            if(currentClass == ActiveRecord.class)//                break;//            else//                currentClass = currentClass.getSuperclass();//        }////        if(objs != null)//            objs.setFieldAccesstorMapping(objects);//        else//        {//            objs = new ObjectInfo();//            objs.setFieldAccesstorMapping(objects);//            ActiveRecord.objectInformationBase.put(object.getClass().getName(), objs);//        }//        return objects;//    }    static ObjectInfo analizeObjectInfo(Class recordType) throws ObjectAnalysisException    {        Class currentClass = recordType;        String recordTypeName = currentClass.getName();        String tableName = null;        ObjectInfo objectInfo = ActiveRecordHelper.activeLibrary.get(recordTypeName);        if(objectInfo != null)            return objectInfo;        //recordTypeName = currentClass.getSimpleName();        objectInfo = new ObjectInfo();        //读取类所关联的表--------------------------------------        table tableAnno = (table)currentClass.getAnnotation(table.class);        if(tableAnno == null)            tableName = currentClass.getSimpleName();        else            tableName = tableAnno.value();        objectInfo.setTableName(tableName);        //建立连接对象的映射表----------------------------------        List<LinkMap> linkMap = new ArrayList<LinkMap>();        has_one one = (has_one)currentClass.getAnnotation(has_one.class);        if(one != null)        for(Class item : one.value())        {            linkMap.add(new LinkMap(item, LinkMap.HasOne));        }        has_many many = (has_many)currentClass.getAnnotation(has_many.class);        if(many != null)        for(Class item : many.value())        {            linkMap.add(new LinkMap(item, LinkMap.HasMany));        }        //--------------------------------------------------        List<Accesstor> accesstorList = new ArrayList<Accesstor>();//缓存对象属性        List<Accesstor> idList = new ArrayList<Accesstor>();//缓存对象ID        //开始读取所有符合规范的字段命名符合JavaBean的命名规范,存取器声明为公开        while(currentClass!=null)        {            if(currentClass.equals(ActiveRecord.class))                break;            for(Field field : currentClass.getDeclaredFields())            {                if(!currentClass.equals(recordType))                    if(field.getModifiers()!=Modifier.PROTECTED && field.getModifiers()!=Modifier.PUBLIC)                        continue;//跳过不可继承的Field                //先检查annotation                column col = field.getAnnotation(column.class);//System.err.println(col);                if(col!=null)                {                    if(column.NonColumn.equals(col.value()))                        continue;                }                link link = field.getAnnotation(link.class);                if(link!=null)//如果link符号存在,则取出该ActiveRecord类的has_xxx映射并存入字段关联                {                    FieldColumnNode fieldNode = new FieldColumnNode();                    fieldNode.setFieldName(field.getName());                    fieldNode.setColumnName(link.refer());//System.err.println(currentClass.getName()+" : "+linkMap.get(0).recordType.getName());                    LinkMap tempLinkMap = findFromList(linkMap, link.value());                    if(tempLinkMap == null)//如果ActiveRecord类并没有声明has_该类,则抛出异常                    {                        throw new ObjectAnalysisException("LinkTypeNotFound: " + link.value().getName());                    }                    if(tempLinkMap.getLinkedField() == null)                         tempLinkMap.setLinkedField(new FieldColumnNode[]{fieldNode});                    else                    {                        int len = tempLinkMap.getLinkedField().length;                        FieldColumnNode[] fms = new FieldColumnNode[len+1];                        int i=0;                        for(;i<len;i++)                            fms[i] = tempLinkMap.getLinkedField()[i];                        fms[i] = fieldNode;                        tempLinkMap.setLinkedField(fms);                    }                }                try                {                    String name = field.getName();                    Method getter = currentClass.getMethod(ActiveRecordHelper.getGetterNameByField(name));                    Method setter = currentClass.getMethod(ActiveRecordHelper.getSetterNameByField(name), field.getType());                    Accesstor attri = new Accesstor(name, getter, setter);                    if(col!=null)                        attri.setColumnName(col.value());                    else                        attri.setColumnName(name);                    id ID = field.getAnnotation(id.class);//判断是否ID                    if(ID!=null)                    {                        idList.add(attri);                    }                    else                        accesstorList.add(attri);                }                catch(Exception err)                {//It means that it's not a valid field                }            }            currentClass = currentClass.getSuperclass();        }        int size = idList.size();        Accesstor[] ids = null;        if(size > 0)        {            ids = new Accesstor[size];            idList.toArray(ids);        }        else//如果没有自定义id,则添加默认id到id列表,并添加id字段到accesstor列表        {            try            {                ids = new Accesstor[]{new Accesstor(Flag.Record.IdName, Flag.Record.IdName, recordType.getMethod(ActiveRecordHelper.getGetterNameByField(Flag.Record.IdName)), recordType.getMethod(ActiveRecordHelper.getSetterNameByField(Flag.Record.IdName), Object.class))};            }            catch(Exception err)            {//It won't happen.                System.err.println(err);            }        }        objectInfo.setIdentify(ids);        objectInfo.setLinkMap(linkMap.toArray(new LinkMap[linkMap.size()]));        Accesstor[] accesstors = new Accesstor[accesstorList.size()];        objectInfo.setAccesstor(accesstorList.toArray(accesstors));        objectInfo.setBasicSqlStatement(SQLCreator.createBasicSQL(tableName, accesstors, ids));//        //构造SQL语句-------------------------------------------------------------------//        BasicSqlStatement stmts = new BasicSqlStatement();//        StringBuffer bufInsert = new StringBuffer(200);//        StringBuffer bufUpdate = new StringBuffer(200);//        StringBuffer bufSelect = new StringBuffer(200);//        StringBuffer bufDelete = new StringBuffer(100);//        //insert语句//        bufInsert.append("insert into ");//        bufInsert.append(tableName);//        bufInsert.append("(");//        //update语句//        bufUpdate.append("update ");//        bufUpdate.append(tableName);//        bufUpdate.append(" set ");//        //select语句//        bufSelect.append("select ");//        //delete语句//        bufDelete.append("delete from ");//        bufDelete.append(tableName);//        int index = 0;//        int idLength = ids.length-1;//        for(index = 0;index<=idLength;index++)//        {//            String columnName = ids[index].getColumnName();//            bufInsert.append(columnName);//            bufSelect.append(columnName);//            bufInsert.append(',');//            bufSelect.append(',');//        }//        int accLength = accesstors.length-1;//        for(index = 0;index<=accLength;index++)//        {//            String columnName = accesstors[index].getColumnName();//            bufInsert.append(columnName);//            bufSelect.append(columnName);//            bufUpdate.append(columnName);//            if(index==accLength)//            {//                bufUpdate.append("=?");//            }//            else//            {//                bufInsert.append(',');//                bufSelect.append(',');//                bufUpdate.append("=?,");//            }//        }//        bufInsert.append(")values(");//        index = idLength+accLength+2;//        for(;index>0;index--)//添加insert语句的占位符//        {//            bufInsert.append('?');//            if(index==1)//                bufInsert.append(')');//            else//                bufInsert.append(',');//        }//        bufSelect.append(" from ");//        bufSelect.append(tableName);//        //where子句//        StringBuffer whereClause = new StringBuffer(50);//        whereClause.append(" where ");//        for(index = 0;index<=idLength;index++)//        {//            whereClause.append(ids[index].getColumnName());//            if(index==idLength)//                whereClause.append("=?");//            else//                whereClause.append("=?,");//        }//        bufUpdate.append(whereClause);//        bufSelect.append(whereClause);//        bufDelete.append(whereClause);//        //-----------------------------------------------------------------------------//        stmts.setInsertStatement(bufInsert.toString());//        stmts.setUpdateStatement(bufUpdate.toString());//        stmts.setSelectStatement(bufSelect.toString());

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -