Search in sources :

Example 6 with DBMeta

use of org.dbflute.dbmeta.DBMeta in project dbflute-core by dbflute.

the class AbstractSqlClause method getClauseQueryInsert.

// ===================================================================================
// Query Update
// ============
// -----------------------------------------------------
// Query Insert
// ------------
public String getClauseQueryInsert(Map<String, String> fixedValueQueryExpMap, SqlClause resourceSqlClause) {
    // at first, this should be called (before on-query name handling)
    // because an on-query name of mapped info are set in this process
    final String resourceViewClause = resourceSqlClause.getClause();
    if (_specifiedSelectColumnMap == null) {
        String msg = "The specified columns for query-insert are required.";
        throw new IllegalConditionBeanOperationException(msg);
    }
    final Map<String, SpecifiedColumn> elementMap = _specifiedSelectColumnMap.get(getBasePointAliasName());
    if (elementMap == null || elementMap.isEmpty()) {
        String msg = "The specified columns of inserted table for query-insert are required.";
        throw new IllegalConditionBeanOperationException(msg);
    }
    final DBMeta dbmeta = getDBMeta();
    final StringBuilder intoSb = new StringBuilder();
    final StringBuilder selectSb = new StringBuilder();
    final String resourceAlias = "dfres";
    int index = 0;
    final List<ColumnInfo> columnInfoList = dbmeta.getColumnInfoList();
    for (ColumnInfo columnInfo : columnInfoList) {
        final String columnDbName = columnInfo.getColumnDbName();
        final SpecifiedColumn specifiedColumn = elementMap.get(columnDbName);
        final String onQueryName;
        if (specifiedColumn != null) {
            onQueryName = specifiedColumn.getValidMappedOnQueryName();
        } else if (fixedValueQueryExpMap.containsKey(columnDbName)) {
            final String fixedValueQueryExp = fixedValueQueryExpMap.get(columnDbName);
            if (fixedValueQueryExp != null) {
                onQueryName = encryptIfNeeds(columnInfo, fixedValueQueryExp);
            } else {
                // it uses null literal on query
                // because the SQL analyzer blocks null parameters
                // (the analyzer should do it for condition-bean)
                onQueryName = "null";
            }
        } else {
            continue;
        }
        if (onQueryName == null || onQueryName.trim().length() == 0) {
            // no way
            String msg = "The on-query name for query-insert is required: " + specifiedColumn;
            throw new IllegalConditionBeanOperationException(msg);
        }
        final ColumnSqlName columnSqlName = columnInfo.getColumnSqlName();
        if (index > 0) {
            intoSb.append(", ");
            selectSb.append(", ");
        }
        intoSb.append(columnSqlName);
        if (specifiedColumn != null) {
            selectSb.append(resourceAlias).append(".");
        }
        selectSb.append(onQueryName);
        ++index;
    }
    final String subQueryIdentity = "queryInsertResource";
    final String subQueryBeginMark = resolveSubQueryBeginMark(subQueryIdentity);
    final String subQueryEndMark = resolveSubQueryEndMark(subQueryIdentity);
    final StringBuilder mainSb = new StringBuilder();
    mainSb.append("insert into ").append(dbmeta.getTableSqlName());
    mainSb.append(" (").append(intoSb).append(")").append(ln());
    mainSb.append("select ").append(selectSb).append(ln());
    mainSb.append("  from (").append(subQueryBeginMark).append(ln());
    mainSb.append(resourceViewClause).append(ln());
    mainSb.append("       ) ").append(resourceAlias).append(subQueryEndMark);
    final String sql = mainSb.toString();
    return processSubQueryIndent(sql);
}
Also used : ColumnSqlName(org.dbflute.dbmeta.name.ColumnSqlName) DBMeta(org.dbflute.dbmeta.DBMeta) IllegalConditionBeanOperationException(org.dbflute.exception.IllegalConditionBeanOperationException) ColumnInfo(org.dbflute.dbmeta.info.ColumnInfo) SpecifiedColumn(org.dbflute.cbean.dream.SpecifiedColumn)

Example 7 with DBMeta

use of org.dbflute.dbmeta.DBMeta in project dbflute-core by dbflute.

the class AbstractBehaviorWritable method helpInsertOrUpdateInternally.

protected <RESULT extends ENTITY> void helpInsertOrUpdateInternally(RESULT entity, InsertOption<CB> insOption, UpdateOption<CB> updOption) {
    assertEntityNotNull(entity);
    if (helpDetermineInsertOrUpdateDirectInsert(entity)) {
        doCreate(entity, insOption);
        return;
    }
    RuntimeException updateException = null;
    try {
        doModify(entity, updOption);
    } catch (EntityAlreadyUpdatedException e) {
        // already updated (or means not found)
        updateException = e;
    } catch (EntityAlreadyDeletedException e) {
        // means not found
        updateException = e;
    } catch (OptimisticLockColumnValueNullException e) {
        // means insert?
        updateException = e;
    }
    if (updateException == null) {
        return;
    }
    final CB cb = newConditionBean();
    final Set<String> uniqueDrivenProperties = entity.myuniqueDrivenProperties();
    if (uniqueDrivenProperties != null && !uniqueDrivenProperties.isEmpty()) {
        for (String prop : uniqueDrivenProperties) {
            final DBMeta dbmeta = entity.asDBMeta();
            final ColumnInfo columnInfo = dbmeta.findColumnInfo(prop);
            // already checked in update process
            final Object value = columnInfo.read(entity);
            cb.localCQ().invokeQueryEqual(columnInfo.getColumnDbName(), value);
        }
    } else {
        cb.acceptPrimaryKeyMap(asDBMeta().extractPrimaryKeyMap(entity));
    }
    if (readCount(cb) == 0) {
        // anyway if not found, insert
        doCreate(entity, insOption);
    } else {
        throw updateException;
    }
}
Also used : DBMeta(org.dbflute.dbmeta.DBMeta) ColumnInfo(org.dbflute.dbmeta.info.ColumnInfo) EntityAlreadyUpdatedException(org.dbflute.exception.EntityAlreadyUpdatedException) EntityAlreadyDeletedException(org.dbflute.exception.EntityAlreadyDeletedException) OptimisticLockColumnValueNullException(org.dbflute.exception.OptimisticLockColumnValueNullException)

Example 8 with DBMeta

use of org.dbflute.dbmeta.DBMeta in project dbflute-core by dbflute.

the class AbstractBehaviorWritable method setupExclusiveControlColumnOfQueryInsert.

protected void setupExclusiveControlColumnOfQueryInsert(Entity entity) {
    final DBMeta dbmeta = asDBMeta();
    if (dbmeta.hasVersionNo()) {
        final ColumnInfo columnInfo = dbmeta.getVersionNoColumnInfo();
        columnInfo.write(entity, InsertOption.VERSION_NO_FIRST_VALUE);
    }
    if (dbmeta.hasUpdateDate()) {
        final ColumnInfo columnInfo = dbmeta.getUpdateDateColumnInfo();
        columnInfo.write(entity, ResourceContext.getAccessTimestamp());
    }
}
Also used : DBMeta(org.dbflute.dbmeta.DBMeta) ColumnInfo(org.dbflute.dbmeta.info.ColumnInfo)

Example 9 with DBMeta

use of org.dbflute.dbmeta.DBMeta in project dbflute-core by dbflute.

the class TnBeanMetaDataFactoryExtension method createBeanMetaDataImpl.

@Override
protected TnBeanMetaDataImpl createBeanMetaDataImpl(Class<?> beanClass) {
    // /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
    // for ConditionBean and insert() and update() and delete() and so on...
    // = = = = = = = = = =/
    final DBMeta dbmeta = provideDBMeta(beanClass);
    return new TnBeanMetaDataImpl(beanClass, dbmeta) {

        /**
         * The internal list of identifier generator. Elements of this list should be added when initializing.
         */
        protected final List<TnIdentifierGenerator> _internalIdentifierGeneratorList = new ArrayList<TnIdentifierGenerator>();

        /**
         * The internal map of identifier generator by property name.
         */
        protected final Map<String, TnIdentifierGenerator> _internalIdentifierGeneratorsByPropertyName = newConcurrentHashMap();

        // /= = = = = = =
        // for cache
        // = = = = =/
        @Override
        public void initialize() {
            // non thread safe so this is called immediately after creation
            final Class<?> myBeanClass = getBeanClass();
            if (isDBFluteEntity(myBeanClass)) {
                final TnBeanMetaData cachedMeta = getMetaFromCache(myBeanClass);
                if (cachedMeta == null) {
                    if (isInternalDebugEnabled()) {
                        _log.debug("...Caching the bean: " + DfTypeUtil.toClassTitle(myBeanClass));
                    }
                    _metaMap.put(myBeanClass, this);
                }
            }
            super.initialize();
        }

        // /= = = = = = =
        // for insert()
        // = = = = =/
        // The attributes 'identifierGenerators' and 'identifierGeneratorsByPropertyName'
        // of super class are unused. It prepares original attributes here.
        @Override
        protected void setupIdentifierGenerator(TnPropertyType propertyType) {
            // only called in the initialize() process
            final DfPropertyDesc pd = propertyType.getPropertyDesc();
            final String propertyName = propertyType.getPropertyName();
            final String idType = _beanAnnotationReader.getId(pd);
            final TnIdentifierGenerator generator = createInternalIdentifierGenerator(propertyType, idType);
            _internalIdentifierGeneratorList.add(generator);
            _internalIdentifierGeneratorsByPropertyName.put(propertyName, generator);
        }

        protected TnIdentifierGenerator createInternalIdentifierGenerator(TnPropertyType propertyType, String idType) {
            return TnIdentifierGeneratorFactory.createIdentifierGenerator(propertyType, idType);
        }

        @Override
        public TnIdentifierGenerator getIdentifierGenerator(int index) {
            return _internalIdentifierGeneratorList.get(index);
        }

        @Override
        public int getIdentifierGeneratorSize() {
            return _internalIdentifierGeneratorList.size();
        }

        @Override
        public TnIdentifierGenerator getIdentifierGenerator(String propertyName) {
            return _internalIdentifierGeneratorsByPropertyName.get(propertyName);
        }
    };
}
Also used : DfPropertyDesc(org.dbflute.helper.beans.DfPropertyDesc) DBMeta(org.dbflute.dbmeta.DBMeta) TnBeanMetaData(org.dbflute.s2dao.metadata.TnBeanMetaData) ArrayList(java.util.ArrayList) List(java.util.List) TnBeanMetaDataImpl(org.dbflute.s2dao.metadata.impl.TnBeanMetaDataImpl) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) TnPropertyType(org.dbflute.s2dao.metadata.TnPropertyType) TnIdentifierGenerator(org.dbflute.s2dao.identity.TnIdentifierGenerator)

Example 10 with DBMeta

use of org.dbflute.dbmeta.DBMeta in project dbflute-core by dbflute.

the class AbstractBehaviorReadable method doHelpLoadReferrerInternally.

protected <// generic
LOCAL_ENTITY extends Entity, // generic
KEY, // generic
REFERRER_CB extends ConditionBean, // generic
REFERRER_ENTITY extends Entity> NestedReferrerListGateway<REFERRER_ENTITY> doHelpLoadReferrerInternally(List<LOCAL_ENTITY> localEntityList, LoadReferrerOption<REFERRER_CB, REFERRER_ENTITY> loadReferrerOption, final String referrerProperty) {
    final DBMeta dbmeta = asDBMeta();
    final ReferrerInfo referrerInfo = dbmeta.findReferrerInfo(referrerProperty);
    final BehaviorReadable referrerBhv = xfindReferrerBehavior(referrerInfo);
    // might be unique key
    final Set<ColumnInfo> pkColSet = referrerInfo.getLocalReferrerColumnInfoMap().keySet();
    // key is referrer's
    final Map<ColumnInfo, ColumnInfo> mappingColMap = referrerInfo.getReferrerLocalColumnInfoMap();
    final InternalLoadReferrerCallback<LOCAL_ENTITY, KEY, REFERRER_CB, REFERRER_ENTITY> callback;
    if (pkColSet.size() == 1) {
        // simple key
        final ColumnInfo pkCol = pkColSet.iterator().next();
        final ColumnInfo fkCol = mappingColMap.keySet().iterator().next();
        callback = xcreateLoadReferrerCallback(referrerProperty, dbmeta, referrerInfo, referrerBhv, pkCol, fkCol);
    } else {
        // compound key
        final Set<ColumnInfo> fkColSet = mappingColMap.keySet();
        callback = xcreateLoadReferrerCallback(referrerProperty, dbmeta, referrerInfo, referrerBhv, pkColSet, fkColSet, mappingColMap);
    }
    return helpLoadReferrerInternally(localEntityList, loadReferrerOption, callback);
}
Also used : DBMeta(org.dbflute.dbmeta.DBMeta) ColumnInfo(org.dbflute.dbmeta.info.ColumnInfo) ReferrerInfo(org.dbflute.dbmeta.info.ReferrerInfo)

Aggregations

DBMeta (org.dbflute.dbmeta.DBMeta)64 ColumnInfo (org.dbflute.dbmeta.info.ColumnInfo)32 ArrayList (java.util.ArrayList)13 ForeignInfo (org.dbflute.dbmeta.info.ForeignInfo)13 List (java.util.List)12 LinkedHashMap (java.util.LinkedHashMap)11 ColumnSqlName (org.dbflute.dbmeta.name.ColumnSqlName)10 Entity (org.dbflute.Entity)9 PrimaryInfo (org.dbflute.dbmeta.info.PrimaryInfo)9 ReferrerInfo (org.dbflute.dbmeta.info.ReferrerInfo)9 Method (java.lang.reflect.Method)8 ReflectionFailureException (org.dbflute.util.DfReflectionUtil.ReflectionFailureException)8 Map (java.util.Map)7 ColumnFunctionCipher (org.dbflute.cbean.cipher.ColumnFunctionCipher)7 RelationInfo (org.dbflute.dbmeta.info.RelationInfo)7 LocalDate (java.time.LocalDate)6 LocalDateTime (java.time.LocalDateTime)6 Collection (java.util.Collection)6 Date (java.util.Date)6 HashMap (java.util.HashMap)6