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

📄 dbdatawriter.java

📁 利用java反射机制
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package org.julp;import java.util.*;import java.sql.*;import java.beans.*;import java.lang.reflect.*;public class DBDataWriter implements DataWriter, java.io.Serializable, Cloneable {           public DBDataWriter() {        if (Boolean.getBoolean("debug-julp") || Boolean.getBoolean("debug-" + getClass().getName())){            debug = true;        }    }        protected int removedCount = 0;    protected int createdCount = 0;    protected int modifiedCount = 0;    protected List objectList = null;    protected List removedObjects = null;    protected List createdObjects = null;    protected List modifiedObjects = null;    protected List generatedSQL = null;    protected MetaData metaData = null;    protected DomainObjectFactory requestor = null;    protected String fullTableName = null;    protected String modifiedCatalog = null;    protected String modifiedSchema = null;    protected String modifiedTable = null;    protected Object[] readArg = new Object[0];    protected boolean debug = false;    protected Throwable whatIsWrong = null;        protected void init(){        removedCount = 0;        createdCount = 0;        modifiedCount = 0;        if (requestor.getMetaData() == null){            requestor.populateMetaData();        }        modifiedCatalog = this.requestor.getCatalog();        modifiedSchema = this.requestor.getSchema();        modifiedTable = this.requestor.getTable();        if (modifiedTable == null) {            throw new NullPointerException("Table name is missing");        }        fullTableName = modifiedTable;        if (modifiedSchema != null) {            fullTableName = modifiedSchema + "." + fullTableName;        }        if (modifiedCatalog != null){            fullTableName = modifiedCatalog + "." + fullTableName;        }    }        public boolean writeData(DomainObjectFactory requestor) throws Exception{        if (requestor.isReadOnly()){            throw new Exception("Read Only");        }        this.requestor = requestor;        this.init();        boolean success = true;        boolean empty = false;        objectList = requestor.getObjectList();        if (objectList == null || objectList.isEmpty()){            empty = true;        }        removedObjects = requestor.getRemovedObjects();        if ((removedObjects == null || removedObjects.isEmpty()) && empty){            return false;        }        if (removedObjects == null) removedObjects = new ArrayList();        if (createdObjects == null) createdObjects = new ArrayList();        if (modifiedObjects == null) modifiedObjects = new ArrayList();                if (requestor.getDataModificationSequence() != null){            Iterator it = objectList.iterator();            while(it.hasNext()){                DomainObject domainObject = (DomainObject) it.next();                if (domainObject.getSqlStatus() == domainObject.DELETED && domainObject.getOriginalValues() != null && domainObject.getOriginalValues().getFieldCount() > 0){                    removedObjects.add(domainObject);                }else if (domainObject.getSqlStatus() == domainObject.UPDATED && domainObject.getOriginalValues() != null && domainObject.getOriginalValues().getFieldCount() > 0){                    modifiedObjects.add(domainObject);                }else if (domainObject.getSqlStatus() == domainObject.INSERTED && domainObject.getOriginalValues() == null || domainObject.getOriginalValues().getFieldCount() < 1){                    createdObjects.add(domainObject);                }            }                        for (int i = 0;i < requestor.getDataModificationSequence().length;i++){                if (requestor.getDataModificationSequence(i) == requestor.DATA_MODIFICATION_SEQUENCE_DELETE){                    removeObjects();                } else if (requestor.getDataModificationSequence(i) == requestor.DATA_MODIFICATION_SEQUENCE_UPDATE){                    storeObjects();                } else if (requestor.getDataModificationSequence(i) == requestor.DATA_MODIFICATION_SEQUENCE_INSERT){                    createObjects();                }            }        }else{ // no DML sequence            objectList.addAll(removedObjects);            Iterator it = objectList.iterator();            while(it.hasNext()){                DomainObject domainObject = (DomainObject) it.next();                if (domainObject.getSqlStatus() == domainObject.DELETED && domainObject.getOriginalValues() != null && domainObject.getOriginalValues().getFieldCount() > 0){                    if (!removeObject(domainObject)){                        return false;                    }                }else if (domainObject.getSqlStatus() == domainObject.UPDATED && domainObject.getOriginalValues() != null && domainObject.getOriginalValues().getFieldCount() > 0){                    if (!storeObject(domainObject)){                        return false;                    }                }else if (domainObject.getSqlStatus() == domainObject.INSERTED && domainObject.getOriginalValues() == null || domainObject.getOriginalValues().getFieldCount() < 1){                    if (!createObject(domainObject)){                        return false;                    }                }else if (domainObject.getSqlStatus() == domainObject.ORIGINAL){                    // do nothing                }else{                    throw new IllegalArgumentException("Invalid SQL status");                }            }        }                return success;    }        protected boolean removeObjects(){        if (removedObjects.isEmpty()){            return true;        }        Iterator iter = removedObjects.iterator();        while (iter.hasNext()){            DomainObject domainObject = (DomainObject) iter.next();            if (!removeObject(domainObject)){                return false;            }        }        return true;    }        protected boolean storeObjects(){        Iterator iter = modifiedObjects.iterator();        while (iter.hasNext()){            DomainObject domainObject = (DomainObject) iter.next();            if (!storeObject(domainObject)){                return false;            }        }        return true;    }        protected boolean createObjects(){        Iterator iter = createdObjects.iterator();        while (iter.hasNext()){            DomainObject domainObject = (DomainObject) iter.next();            if (!createObject(domainObject)){                return false;            }        }        return true;    }        protected boolean removeObject(DomainObject domainObject){        String fieldName = null;        List params = new ArrayList();        try{            StringBuffer sql = new StringBuffer("DELETE FROM ");            sql.append(fullTableName);            sql.append(" WHERE ");            /* Always use PrimaryKeys columns in WHERE statement */            List pk = PKCache.getInstance().getPrimaryKey(modifiedCatalog, modifiedSchema, modifiedTable);            Iterator iter = pk.iterator();            while (iter.hasNext()){                String columnName = (String) iter.next();   // this is full column name                fieldName = (String) requestor.getMapping().get(columnName);                int index = requestor.getMetaData().getColumnIndexByFieldName(fieldName);                Method readMethod = requestor.getMetaData().getReadMethod(index);                                Object origValue = domainObject.getOriginalValue(fieldName);                if (origValue == null){                    sql.append(columnName).append(" IS NULL AND ");                }else{                    sql.append(columnName).append(" = ? AND ");                    params.add(origValue);                }            }                      if (requestor.getOptimisticLock() == requestor.KEY_COLUMNS){ /* built already */                            /* For DELETE make KEY_AND_MODIFIED_COLUMNS and KEY_AND_UPDATEBLE_COLUMNS the same: include all table columns in WHERE statement */            }else if (requestor.getOptimisticLock() == requestor.KEY_AND_MODIFIED_COLUMNS || requestor.getOptimisticLock() == requestor.KEY_AND_UPDATEBLE_COLUMNS){                for (int i = 1;i <= requestor.getMetaData().getColumnCount();i++){                    String catalog = requestor.getMetaData().getCatalogName(i);                    String schema = requestor.getMetaData().getSchemaName(i);                    String table = requestor.getMetaData().getTableName(i);                    if (modifiedCatalog != null){                        if (!modifiedCatalog.equals(catalog)){                            continue;                        }                    }                    if (modifiedSchema != null){                        if (!modifiedSchema.equals(schema)){                            continue;                        }                    }                    if (modifiedTable != null){                        if (!modifiedTable.equals(table)){                            continue;                        }                    }                                 String columnName = requestor.getMetaData().getFullColumnName(i);                                        if (sql.indexOf(columnName) > -1){                        continue;// this is PK column - proccesed already                    }                    if (!requestor.getMetaData().isWritable(i) || requestor.getMetaData().isReadOnly(i)){                        continue;                    }                    fieldName = requestor.getMetaData().getFieldName(i);                    Object value = requestor.getMetaData().getReadMethod(i).invoke(domainObject, readArg);                                        Object origValue = domainObject.getOriginalValue(fieldName);                    if (origValue == null){                        sql.append(columnName).append(" IS NULL AND ");                    }else{                        sql.append(columnName).append(" = ? AND ");                        params.add(origValue);                    }                                    }            }else{                throw new IllegalArgumentException("Invalid Optimistic Lock settings");            }            int len = sql.length();            sql = sql.delete(len - 5, len - 1);            System.out.println("removeObject: " + sql + "; params: " + params);            if (requestor.isGenerateSQLOnly()){                if (generatedSQL == null){                    generatedSQL = new ArrayList();                }                Object[] entry = new Object[2];                entry[0] = sql.toString();                entry[1] = params.toArray();                generatedSQL.add(entry);            }else{                int rowsAffected = requestor.getDBServices().execute(sql.toString(), params);                setRemovedCount(removedCount + rowsAffected);                if (requestor.isThrowOptimisticLockDeleteException() && rowsAffected != 1){                    return false;                }            }        }catch(Exception e){            setWhatIsWrong(e);            e.printStackTrace();            return false;        }        return true;    }        protected boolean storeObject(DomainObject domainObject){        String fieldName = null;        List params = new ArrayList();        if (debug) System.out.println("julp ============= " + new java.util.Date() + " " + this.getClass() + "::storeObject ===================");        try{            StringBuffer sql = new StringBuffer("UPDATE ");            sql.append(fullTableName).append(" SET ");            for (int i = 1;i <= requestor.getMetaData().getColumnCount();i++){                String catalog = requestor.getMetaData().getCatalogName(i);                String schema = requestor.getMetaData().getSchemaName(i);                String table = requestor.getMetaData().getTableName(i);                if (modifiedCatalog != null){                    if (!modifiedCatalog.equals(catalog)){                        continue;                    }                }                if (modifiedSchema != null){                    if (!modifiedSchema.equals(schema)){                        continue;                    }                }                if (modifiedTable != null){                    if (!modifiedTable.equals(table)){                        continue;                    }                }                                               if (!requestor.getMetaData().isWritable(i) || requestor.getMetaData().isReadOnly(i)){                    continue;                }                String columnName = null;                if (requestor.isNoFullColumnName()){                    columnName = requestor.getMetaData().getColumnName(i);                }else{                    columnName = requestor.getMetaData().getFullColumnName(i);                }                                fieldName = requestor.getMetaData().getFieldName(i);                Object value = requestor.getMetaData().getReadMethod(i).invoke(domainObject, readArg);                                Object origValue = domainObject.getOriginalValue(fieldName);                if (debug) System.out.println("julp ============= " + new java.util.Date() + " " + this.getClass() + "::storeObject::fieldName: " + fieldName + " value: " + value + " origValue: " + origValue + " isWritable: " + requestor.getMetaData().isWritable(i) + " isReadOnly: " + requestor.getMetaData().isReadOnly(i) + " ===================");                if (origValue == null){                    if (value == null){                        continue; // the same value - do not include in update                    }else{                        sql.append(columnName).append(" = ?, ");                        params.add(value);                    }                }else{                    if (value == null){                        sql.append(columnName).append(" = NULL, ");                    }else{                        if (!origValue.equals(value)){                            sql.append(columnName).append(" = ?, ");                            params.add(value);                        }else{                            continue;                        }                    }                }            }            int idx = sql.lastIndexOf(", ");            if (idx > -1){                sql = sql.delete(idx, idx + 2);            }else{ // No modified column's data                domainObject.setSqlStatus(domainObject.ORIGINAL);                return true;            }            /* Building WHERE */            /* Always use PrimaryKeys columns in WHERE statement */            StringBuffer where = new StringBuffer(" WHERE ");            List pk = PKCache.getInstance().getPrimaryKey(modifiedCatalog, modifiedSchema, modifiedTable);            if (debug) System.out.println("julp ============= " + new java.util.Date() + " " + this.getClass() + "::storeObject::pk: " + pk + " modifiedSchema: " + modifiedSchema + " modifiedTable: " + modifiedTable);            Iterator iter = pk.iterator();            while (iter.hasNext()){                String columnName = (String) iter.next();                fieldName = (String) requestor.getMapping().get(columnName);                if (debug) System.out.println("julp ============= " + new java.util.Date() + " " + this.getClass() + "::storeObject::columnName: " + columnName + " fieldName: " + fieldName);                int index = requestor.getMetaData().getColumnIndexByFieldName(fieldName);                Object origValue = domainObject.getOriginalValue(fieldName);                if (origValue == null){                    where.append(columnName).append(" IS NULL AND ");                }else{                    where.append(columnName).append(" = ? AND ");                    params.add(origValue);                }            }            if (requestor.getOptimisticLock() == requestor.KEY_COLUMNS){                idx = where.lastIndexOf(" AND ");                where = where.delete(idx + 1, idx + 5);            }            if (requestor.getOptimisticLock() == requestor.KEY_COLUMNS){                /* ... built already */

⌨️ 快捷键说明

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