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

📄 genericdao.java

📁 Sequoia ERP是一个真正的企业级开源ERP解决方案。它提供的模块包括:电子商务应用(e-commerce), POS系统(point of sales),知识管理,存货与仓库管理
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/* * $Id: GenericDAO.java 6096 2005-11-09 01:41:31Z jonesde $ * * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR * THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */package org.ofbiz.entity.datasource;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Timestamp;import java.util.Collection;import java.util.Collections;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeSet;import java.util.LinkedList;import javolution.util.FastList;import javolution.util.FastMap;import javolution.util.FastSet;import org.ofbiz.base.util.Debug;import org.ofbiz.base.util.UtilValidate;import org.ofbiz.entity.EntityLockedException;import org.ofbiz.entity.GenericDataSourceException;import org.ofbiz.entity.GenericDelegator;import org.ofbiz.entity.GenericEntity;import org.ofbiz.entity.GenericEntityException;import org.ofbiz.entity.GenericEntityNotFoundException;import org.ofbiz.entity.GenericModelException;import org.ofbiz.entity.GenericNotImplementedException;import org.ofbiz.entity.GenericValue;import org.ofbiz.entity.condition.EntityCondition;import org.ofbiz.entity.condition.EntityConditionParam;import org.ofbiz.entity.condition.EntityFieldMap;import org.ofbiz.entity.condition.EntityOperator;import org.ofbiz.entity.config.DatasourceInfo;import org.ofbiz.entity.config.EntityConfigUtil;import org.ofbiz.entity.jdbc.DatabaseUtil;import org.ofbiz.entity.jdbc.SQLProcessor;import org.ofbiz.entity.jdbc.SqlJdbcUtil;import org.ofbiz.entity.model.ModelEntity;import org.ofbiz.entity.model.ModelField;import org.ofbiz.entity.model.ModelFieldTypeReader;import org.ofbiz.entity.model.ModelKeyMap;import org.ofbiz.entity.model.ModelRelation;import org.ofbiz.entity.model.ModelViewEntity;import org.ofbiz.entity.transaction.TransactionUtil;import org.ofbiz.entity.util.EntityFindOptions;import org.ofbiz.entity.util.EntityListIterator;/** * Generic Entity Data Access Object - Handles persisntence for any defined entity. * * @author     <a href="mailto:jonesde@ofbiz.org">David E. Jones</a> * @author     <a href="mailto:jaz@ofbiz.org">Andy Zeneski</a> * @author     <a href="mailto:chris_maurer@altavista.com">Chris Maurer</a> * @author     <a href="mailto:jdonnerstag@eds.de">Juergen Donnerstag</a> * @author     <a href="mailto:gielen@aixcept.de">Rene Gielen</a> * @author     <a href="mailto:john_nutting@telluridetechnologies.com">John Nutting</a> * @version    $Rev: 6096 $ * @since      1.0 */public class GenericDAO {    public static final String module = GenericDAO.class.getName();    protected static Map genericDAOs = FastMap.newInstance();    protected String helperName;    protected ModelFieldTypeReader modelFieldTypeReader = null;    protected DatasourceInfo datasourceInfo;    public static GenericDAO getGenericDAO(String helperName) {        GenericDAO newGenericDAO = (GenericDAO) genericDAOs.get(helperName);        if (newGenericDAO == null) { // don't want to block here            synchronized (GenericDAO.class) {                newGenericDAO = (GenericDAO) genericDAOs.get(helperName);                if (newGenericDAO == null) {                    newGenericDAO = new GenericDAO(helperName);                    genericDAOs.put(helperName, newGenericDAO);                }            }        }        return newGenericDAO;    }    public GenericDAO(String helperName) {        this.helperName = helperName;        this.modelFieldTypeReader = ModelFieldTypeReader.getModelFieldTypeReader(helperName);        this.datasourceInfo = EntityConfigUtil.getDatasourceInfo(helperName);    }    private void addFieldIfMissing(List fieldsToSave, String fieldName, ModelEntity modelEntity) {        Iterator fieldsToSaveIter = fieldsToSave.iterator();        while (fieldsToSaveIter.hasNext()) {            ModelField fieldToSave = (ModelField) fieldsToSaveIter.next();            if (fieldName.equals(fieldToSave.getName())) {                return;            }        }        // at this point we didn't find it        fieldsToSave.add(modelEntity.getField(fieldName));    }    public int insert(GenericEntity entity) throws GenericEntityException {        ModelEntity modelEntity = entity.getModelEntity();        if (modelEntity == null) {            throw new GenericModelException("Could not find ModelEntity record for entityName: " + entity.getEntityName());        }        SQLProcessor sqlP = new SQLProcessor(helperName);        try {            return singleInsert(entity, modelEntity, modelEntity.getFieldsCopy(), sqlP);        } catch (GenericEntityException e) {            sqlP.rollback();            throw new GenericEntityException("Exception while inserting the following entity: " + entity.toString(), e);        } finally {            sqlP.close();        }    }    private int singleInsert(GenericEntity entity, ModelEntity modelEntity, List fieldsToSave, SQLProcessor sqlP) throws GenericEntityException {        if (modelEntity instanceof ModelViewEntity) {            return singleUpdateView(entity, (ModelViewEntity) modelEntity, fieldsToSave, sqlP);        }        // if we have a STAMP_TX_FIELD or CREATE_STAMP_TX_FIELD then set it with NOW, always do this before the STAMP_FIELD        // NOTE: these fairly complicated if statements have a few objectives:        //   1. don't run the TransationUtil.getTransaction*Stamp() methods when we don't need to        //   2. don't set the stamp values if it is from an EntitySync (ie maintain original values), unless the stamps are null then set it anyway, ie even if it was from an EntitySync (also used for imports and such)        boolean stampTxIsField = modelEntity.isField(ModelEntity.STAMP_TX_FIELD);        boolean createStampTxIsField = modelEntity.isField(ModelEntity.CREATE_STAMP_TX_FIELD);        if ((stampTxIsField || createStampTxIsField) && (!entity.getIsFromEntitySync() || (stampTxIsField && entity.get(ModelEntity.STAMP_TX_FIELD) == null) || (createStampTxIsField && entity.get(ModelEntity.CREATE_STAMP_TX_FIELD) == null))) {            Timestamp txStartStamp = TransactionUtil.getTransactionStartStamp();            if (stampTxIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_TX_FIELD) == null)) {                entity.set(ModelEntity.STAMP_TX_FIELD, txStartStamp);                addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_TX_FIELD, modelEntity);            }            if (createStampTxIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.CREATE_STAMP_TX_FIELD) == null)) {                entity.set(ModelEntity.CREATE_STAMP_TX_FIELD, txStartStamp);                addFieldIfMissing(fieldsToSave, ModelEntity.CREATE_STAMP_TX_FIELD, modelEntity);            }        }        // if we have a STAMP_FIELD or CREATE_STAMP_FIELD then set it with NOW        boolean stampIsField = modelEntity.isField(ModelEntity.STAMP_FIELD);        boolean createStampIsField = modelEntity.isField(ModelEntity.CREATE_STAMP_FIELD);        if ((stampIsField || createStampIsField)  && (!entity.getIsFromEntitySync() || (stampIsField && entity.get(ModelEntity.STAMP_FIELD) == null) || (createStampIsField && entity.get(ModelEntity.CREATE_STAMP_FIELD) == null))) {            Timestamp startStamp = TransactionUtil.getTransactionUniqueNowStamp();            if (stampIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_FIELD) == null)) {                entity.set(ModelEntity.STAMP_FIELD, startStamp);                addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_FIELD, modelEntity);            }            if (createStampIsField && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.CREATE_STAMP_FIELD) == null)) {                entity.set(ModelEntity.CREATE_STAMP_FIELD, startStamp);                addFieldIfMissing(fieldsToSave, ModelEntity.CREATE_STAMP_FIELD, modelEntity);            }        }        String sql = "INSERT INTO " + modelEntity.getTableName(datasourceInfo) + " (" + modelEntity.colNameString(fieldsToSave) + ") VALUES (" +            modelEntity.fieldsStringList(fieldsToSave, "?", ", ") + ")";        try {            sqlP.prepareStatement(sql);            SqlJdbcUtil.setValues(sqlP, fieldsToSave, entity, modelFieldTypeReader);            int retVal = sqlP.executeUpdate();            entity.synchronizedWithDatasource();            return retVal;        } catch (GenericEntityException e) {            throw new GenericEntityException("while inserting: " + entity.toString(), e);        } finally {            sqlP.close();        }    }    public int updateAll(GenericEntity entity) throws GenericEntityException {        ModelEntity modelEntity = entity.getModelEntity();        if (modelEntity == null) {            throw new GenericModelException("Could not find ModelEntity record for entityName: " + entity.getEntityName());        }        return customUpdate(entity, modelEntity, modelEntity.getNopksCopy());    }    public int update(GenericEntity entity) throws GenericEntityException {        ModelEntity modelEntity = entity.getModelEntity();        if (modelEntity == null) {            throw new GenericModelException("Could not find ModelEntity record for entityName: " + entity.getEntityName());        }        // we don't want to update ALL fields, just the nonpk fields that are in the passed GenericEntity        List partialFields = FastList.newInstance();        Collection keys = entity.getAllKeys();        Iterator nopkIter = modelEntity.getNopksIterator();        while (nopkIter.hasNext()) {            ModelField curField = (ModelField) nopkIter.next();            if (keys.contains(curField.getName())) {                partialFields.add(curField);            }        }        return customUpdate(entity, modelEntity, partialFields);    }    private int customUpdate(GenericEntity entity, ModelEntity modelEntity, List fieldsToSave) throws GenericEntityException {        SQLProcessor sqlP = new SQLProcessor(helperName);        try {            return singleUpdate(entity, modelEntity, fieldsToSave, sqlP);        } catch (GenericEntityException e) {            sqlP.rollback();            throw new GenericEntityException("Exception while updating the following entity: " + entity.toString(), e);        } finally {            sqlP.close();        }    }    private int singleUpdate(GenericEntity entity, ModelEntity modelEntity, List fieldsToSave, SQLProcessor sqlP) throws GenericEntityException {        if (modelEntity instanceof ModelViewEntity) {            return singleUpdateView(entity, (ModelViewEntity) modelEntity, fieldsToSave, sqlP);        }        // no non-primaryKey fields, update doesn't make sense, so don't do it        if (fieldsToSave.size() <= 0) {            if (Debug.verboseOn()) Debug.logVerbose("Trying to do an update on an entity with no non-PK fields, returning having done nothing; entity=" + entity, module);            // returning one because it was effectively updated, ie the same thing, so don't trigger any errors elsewhere            return 1;        }        if (modelEntity.lock()) {            GenericEntity entityCopy = GenericEntity.createGenericEntity(entity);            select(entityCopy, sqlP);            Object stampField = entity.get(ModelEntity.STAMP_FIELD);            if ((stampField != null) && (!stampField.equals(entityCopy.get(ModelEntity.STAMP_FIELD)))) {                String lockedTime = entityCopy.getTimestamp(ModelEntity.STAMP_FIELD).toString();                throw new EntityLockedException("You tried to update an old version of this data. Version locked: (" + lockedTime + ")");            }        }        // if we have a STAMP_TX_FIELD then set it with NOW, always do this before the STAMP_FIELD        // NOTE: these fairly complicated if statements have a few objectives:        //   1. don't run the TransationUtil.getTransaction*Stamp() methods when we don't need to        //   2. don't set the stamp values if it is from an EntitySync (ie maintain original values), unless the stamps are null then set it anyway, ie even if it was from an EntitySync (also used for imports and such)        if (modelEntity.isField(ModelEntity.STAMP_TX_FIELD) && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_TX_FIELD) == null)) {            entity.set(ModelEntity.STAMP_TX_FIELD, TransactionUtil.getTransactionStartStamp());            addFieldIfMissing(fieldsToSave, ModelEntity.STAMP_TX_FIELD, modelEntity);        }        // if we have a STAMP_FIELD then update it with NOW.        if (modelEntity.isField(ModelEntity.STAMP_FIELD) && (!entity.getIsFromEntitySync() || entity.get(ModelEntity.STAMP_FIELD) == null)) {

⌨️ 快捷键说明

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