Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  Copyright 2009-2014 Pavel Ponec
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */
 package org.ujorm.orm.metaModel;
 
 import java.util.List;
 import java.util.Map;
 import org.ujorm.Key;
 import org.ujorm.Ujo;
DB table or view meta-model.

Author(s):
Pavel Ponec
Composed:
1 - * MetaRelation2Many
Composed:
1 - * MetaColumn
Composed:
1 - 1 MetaPKey
Composed:
1 - * MetaIndex
 
 final public class MetaTable extends AbstractMetaModel implements TableWrapper {
     private static final Class<MetaTableCLASS = MetaTable.class;

    
Property Factory
 
     private static final KeyFactory<MetaTablefa = KeyFactory.CamelBuilder.get();
    
The meta-model id
 
     @XmlAttribute
     public static final Key<MetaTable,StringID = .newKey("id".);
    
DB table name
 
     public static final Key<MetaTable,StringNAME = .newKey("name".);
    
The unique table/view name over all Databases in scope one OrmHandler
 
     public static final Key<MetaTable,StringALIAS = .newKey("alias".);
    
Name of table schema.
 
     public static final Key<MetaTable,StringSCHEMA = .newKey("schema".);
    
The state read-only for the database.
 
     public static final Key<MetaTable,BooleanREAD_ONLY = .newKey("readOnly"false);
    
A policy to defining the database structure by a DDL.

See also:
org.ujorm.orm.ao.Orm2ddlPolicy Parameter values
 
     public static final Key<MetaTable,Orm2ddlPolicyORM2DLL_POLICY = .newKey("orm2ddlPolicy".);
    
Name of DB sequence. The value is not used by default, however a special implementation of the UjoSequencer can do it.
 
     public static final Key<MetaTable,StringSEQUENCE = .newKey("sequence".);
    
Is the current object a model of a database view ?
 
     @XmlAttribute
     public static final Key<MetaTable,BooleanVIEW = .newKey("view"false);
    
SQL SELECT statement
 
     public static final Key<MetaTable,StringSELECT = .newKey("select""");
    
Comment of the database table
 
     public static final Key<MetaTable,StringCOMMENT = .newKey("comment".);
    
Table Columns (no relations)
 
     public static final ListKey<MetaTable,MetaColumnCOLUMNS = .newListKey("column");
    
Table relations to many
 
     public static final ListKey<MetaTable,MetaRelation2ManyRELATIONS = .newListKey("relation2m");
    
SQL SELECT model. Note: this key must not be persistent due a blank spaces in key names!
 
     @Transient
     public static final Key<MetaTable,MetaSelectSELECT_MODEL = .newKey("selectModel");
    
Unique Primary Key
 
     @Transient
     public static final Key<MetaTable,MetaPKeyPK = .newKey("pk");
    
Database relative key (a base definition of table)
 
     @Transient
    public static final Key<MetaTable,RelationToManyDB_PROPERTY = .newKey("dbProperty");
    
Database
    @Transient
    public static final Key<MetaTable,MetaDatabaseDATABASE = .newKey("database");

    
The Key initialization
    static{.lock();}

    
Ujo sequencer
    final private UjoSequencer sequencer;

    
Cache of the parameter.
    private Boolean sequenceSchemaSymbol;

    
No parameter constructor.
    public MetaTable() {
         = null;
    }

    
Create new MetaTable.

Parameters:
database Database for the table
dbProperty Configuration key
parTable Configuration data from a XML file
    @SuppressWarnings({"unchecked""LeakingThisInConstructor"})
    public MetaTable(MetaDatabase databaseRelationToMany<?,?> dbPropertyMetaTable parTable) {
         = database.createSequencer(this);
        .setValue(thisdbProperty.getName());
        .setValue(thisdatabase);
        .setValue(thisdbProperty);
        final Field field = UjoManager.getInstance().getPropertyField(..of(database), dbProperty);
        View view1 = field!=null ? field.getAnnotation(View.class) : null;
        View view2 = (ViewdbProperty.getItemType().getAnnotation(View.class);
        .setValue(thisview1!=null || view2!=null);
        if (parTable!=null) {
            changeDefault(this  , .of(parTable));
            changeDefault(this , .of(parTable));
            changeDefault(this.of(parTable));
            changeDefault(this.of(parTable));
            changeDefault(this.of(parTable));
            changeDefault(this,.of(parTable));
            changeDefault(this.of(parTable));
            changeDefault(this  , .of(parTable));
            changeDefault(this.of(parTable));
        }
        if (.of(this)) {
            if (view1!=nullchangeDefault(this  , view1.name());
            if (view1!=nullchangeDefault(this  , view1.value());
            if (view1!=nullchangeDefault(this , view1.alias());
            if (view1!=nullchangeDefault(thisview1.schema());
            if (view1!=nullchangeDefault(thisview1.select());
            if (view2!=nullchangeDefault(this  , view2.name());
            if (view2!=nullchangeDefault(this  , view2.value());
            if (view2!=nullchangeDefault(this , view2.alias());
            if (view2!=nullchangeDefault(thisview2.schema());
            if (view2!=nullchangeDefault(thisview2.select());
        } else {
            Table table1 = field!=null ? field.getAnnotation(Table.class) : null;
            Table table2 = (TabledbProperty.getItemType().getAnnotation(Table.class);
            if (table1!=nullchangeDefault(this  , table1.name());
            if (table1!=nullchangeDefault(this  , table1.value());
            if (table1!=nullchangeDefault(this , table1.alias());
            if (table1!=nullchangeDefault(thistable1.schema());
            if (table1!=nullchangeDefault(thistable1.readOnly());
            if (table1!=nullchangeDefault(thistable1.orm2ddlPolicy());
            if (table1!=nullchangeDefault(this,table1.sequence());
            if (table2!=nullchangeDefault(this  , table2.name());
            if (table2!=nullchangeDefault(this  , table2.value());
            if (table2!=nullchangeDefault(this , table2.alias());
            if (table2!=nullchangeDefault(thistable2.schema());
            if (table2!=nullchangeDefault(thistable2.readOnly());
            if (table2!=nullchangeDefault(thistable2.orm2ddlPolicy());
            if (table2!=nullchangeDefault(this,table2.sequence());
        }
        changeDefault(this..of(database));
        changeDefault(this..of(database));
        changeDefault(this..of(database));
        changeDefault(thisdbProperty.getName());
        String aliasPrefix = ..of(database.getParams());
        String aliasSuffix = ..of(database.getParams());
        changeDefault(thisaliasPrefix+.of(this)+aliasSuffix);
        // Assign Comments:
        Comment comment1 = field!=null ? field.getAnnotation(Comment.class) : null;
        Comment comment2 = (CommentdbProperty.getItemType().getAnnotation(Comment.class);
        if (comment1!=nullchangeDefault(this  , comment1.value());
        if (comment2!=nullchangeDefault(this  , comment2.value());
        if (.of(this) && !.isDefault(this)) {
            .setValue(thisnew MetaSelect(this));
        }
        // -----------------------------------------------
        MetaPKey dpk = new MetaPKey(this);
        .setValue(thisdpk);
        OrmHandler dbHandler = database.getOrmHandler();
        UjoManager ujoManager = UjoManager.getInstance();
        UjoManager.newInstance(dbProperty.getItemType()); // Initialize static Keys
        for (Key key : ujoManager.readKeys(dbProperty.getItemType())) {
            if (!ujoManager.isTransient(key)) {
                if (key instanceof RelationToMany) {
                    MetaRelation2Many param = parTable!=null ? parTable.findRelation(key.getName()) : null;
                    MetaRelation2Many column = new MetaRelation2Many(thiskeyparam);
                    .addItem(thiscolumn);
                    dbHandler.addColumnModel(column);
                } else {
                    MetaColumn param  = parTable!=null ? parTable.findColumn(key.getName()) : null;
                    MetaColumn column = new MetaColumn(thiskeyparam);
                    .addItem(thiscolumn);
                    dbHandler.addColumnModel(column);
                    if (..of(column)) {
                        ..addItem(dpkcolumn);
                    }
                }
            }
        }
    }

    
Assign a PK from framework
    public void assignPrimaryKey(final OrmUjo bofinal Session session) {
        final Class type = getType();
        if (type.isInstance(bo)) {
            try {
               final MetaPKey pk = .of(this);
               pk.assignPrimaryKey(bosession);
            } catch (Throwable e) {
               throw new IllegalArgumentException("DB SEQUENCE is not supported for " + typee);
            }
        } else {
            throw new IllegalArgumentException("Argument is not type of " + type);
        }
    }

    
Returns a new instance or the BO.
        final OrmUjo result = getType().newInstance();
        return result;
    }

    
Returns a base table class.
    @SuppressWarnings("unchecked")
    final public Class<OrmUjogetType() {
        return .of(this).getItemType();
    }

    
Returns the first PK
    public MetaColumn getFirstPK() {
        return .of(this).getFirstColumn();
    }

    
Is the instance a database relation model?
    public boolean isPersistent() {
        return .of(this)!=null;
    }

    
Has this table assigned the database default database schema ?
    public boolean isDefaultSchema() {
        if (==null) {
        }
        if () {
            final String tableSchema = .of(this);
            final String defaultSchema = ..of(getDatabase());
            return tableSchema.equals(defaultSchema);
        } else {
            return false;
        }
    }

    
Is the current object a model of a database view ?
    @Override
    public boolean isView() {
        return .of(this);
    }

    
Is the instance a database persistent table? The false value means that the object is a relation model or a view.
    public boolean isTable() {
        return isPersistent() && !isView();
    }

    
Has the instance assigned a non empty comment?
    public boolean isCommented() {
        return !.isDefault(this);
    }

    
Get a Comment from meta-model annotation.

    public String getComment() {
        return .of(this);
    }

    
Is the query from a SQL select model ?
    public boolean isSelectModel() {
        return .of(this)!=null;
    }

    
Database model is not persistent. A side efect is that the DATABASE key has hot a null value.
    public void setNotPersistent() {
        .setValue(thisnull);
    }

    
Returns a unique table name over all Databases of the one OrmHandler.
    public String getAlias() {
        return .of(this);
    }

    
Returns the database
    final public MetaDatabase getDatabase() {
        return .of(this);
    }

    
Compare object by the same instance.
    @Override
    @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
    public boolean equals(Object obj) {
        return this==obj;
    }

    
Finds the first column by ID or returns null. The method is for internal use only.
        if (OrmTools.isFilled(id)) for (MetaColumn column : .of(this)) {
            if (..equals(columnid)) {
                return column;
            }
        }
        return null;
    }

    
Finds the first relation by ID or returns null. The method is for internal use only.
        if (OrmTools.isFilled(id)) for (MetaRelation2Many relation : .of(this)) {
            if (..equals(relationid)) {
                return relation;
            }
        }
        return null;
    }

    
Get all foreign columns
    public List<MetaColumngetForeignColumns() {
        final List<MetaColumnresult = new ArrayList<MetaColumn>();
        for (MetaColumn column : .getList(this)) {
            if (column.isForeignKey()) {
                result.add(column);
            }
        }
        return result;
    }

    
UJO sequencer
    public UjoSequencer getSequencer() {
        return ;
    }

    
Create an Index For the Column
    public MetaIndex createIndexForColumn(String idxNameMetaColumn column) {
        MetaIndex mIndex = new MetaIndex(idxNamethis);
        boolean isUniqueIndexExists = ..of(column).length() > 0;
        ..setValue(mIndexisUniqueIndexExists);
        return mIndex;
    }

    
Create an Index For the Column
    public String createIndexNameForColumn(MetaColumn columnboolean uniqueIndex) {
        String metaIdxName;
        if (uniqueIndex) {
            metaIdxName = ..of(column);
        } else {
            metaIdxName = ..of(column);
        }
        if (metaIdxName.length() == 0 && column.isForeignKey()) {
            metaIdxName = "AUTO";
        }
        assert metaIdxName.length() > 0;
        // automatic indexes ("AUTO" or foreign keys)
        if (..equalsIgnoreCase(metaIdxName)) {
            final SqlNameProvider nameProvider = getDatabase().getDialect().getNameProvider();
            if (uniqueIndex) {
                metaIdxName = nameProvider.getUniqueConstraintName(column);
            } else {
                metaIdxName = nameProvider.getIndexName(column);
            }
        }
        return metaIdxName;
    }

    
Create a new collection of the table indexes.
        final boolean extendedStrategy = .
        .of(.of(this).getOrmHandler().getParameters());
        return extendedStrategy
             ? getIndexCollectionExtended()
             : getIndexCollectionOriginal() ;
    }

    
Create a new collection of the table indexes.
The extended index name strategy.
        Map<String,MetaIndexmapIndex = new HashMap<String,MetaIndex>();
        for (MetaColumn column : .getList(this)) {
            final String metaUdxName = ..of(column);
            final String metaIdxName = ..of(column);
            final boolean indexExists = metaIdxName.length() > 0;
            final boolean uniqueIndexExists = metaUdxName.length() > 0;
            if (indexExists || column.isForeignKey()) {
                addIndex(columnmapIndexfalse);
            }
            if (uniqueIndexExists) {
                addIndex(columnmapIndextrue);
            }
        }
        return mapIndex.values();
    }

    
Create a new collection of the table indexes.

The original Ujorm solution.
        Map<String,MetaIndexmapIndex = new HashMap<String,MetaIndex>();
        for (MetaColumn column : .getList(this)) {
            String[] idxs = {..of(column), ..of(column)};
            for (int i=0; i<2; ++i) {
                if (idxs[i].length()>0) {
                    String upperIdx = idxs[i].toUpperCase();
                    MetaIndex mIndex = mapIndex.get(upperIdx);
                    if (mIndex==null) {
                        mIndex = new MetaIndex(idxs[i], this);
                        mapIndex.put(upperIdxmIndex);
                    }
                    if (i==0) {
                        ..setValue(mIndexfalse);
                    } else if (upperIdx.equalsIgnoreCase(idxs[0])) {
                        break// Ignore the same column in the index.
                    }
                    ..addItem(mIndexcolumn);
                }
            }
        }
        return mapIndex.values();
    }

    
Add new index
    private void addIndex(MetaColumn columnMap<StringMetaIndexmapIndexboolean uniqueIndex) {
        String idxName = createIndexNameForColumn(columnuniqueIndex);
        MetaIndex mIndex = mapIndex.get(idxName);
        if (mIndex == null) {
            mIndex = createIndexForColumn(idxNamecolumn);
            mapIndex.put(idxNamemIndex);
        }
        ..addItem(mIndexcolumn);
    }

    
Returns a parent of the parameter or the null if no parent was not found.
The method provides a parent in case of emulated inheritance.
    public OrmUjo getParent(final OrmUjo bo) {
        final MetaColumn metaColumn = getFirstPK();
        if (metaColumn.isForeignKey()) {
            return (OrmUjometaColumn.getValue(bo);
        } else {
            return null;
        }
    }

    
Have the table got a READ-ONLU mode ?
    public boolean isReadOnly() {
        return .of(this);
    }

    
Asssert that the table may be changed.
    public void assertChangeAllowed() {
        if (isReadOnly()) {
            final String msg = "The table '" + .of(this) + "' have got the READ-ONLY mode. Check the Ujorm meta-model configuration.";
            throw new IllegalStateException(msg);
        }
    }

    
Returns Orm2DDl policy
    public Orm2ddlPolicy getOrm2ddlPolicy() {
        return .of(this);
    }

    
Return an instance of Meta Model
    @Override
    public MetaTable getModel() {
        return this;
    }

    
Returns all columns
    @Override
    public List<? extends ColumnWrappergetColumns() {
        return ..getList(this);
    }

    
Unlock the meta-model, the method is for internal use only. The method must be enabled by parameter: MoreParams.ENABLE_TO_UNLOCK_IMMUTABLE_METAMODEL.
    public void clearReadOnly() {
        super.clearReadOnly(this.getDatabase().getOrmHandler());
    }

    
Add alias name to the new object
    public TableWrapper addAlias(final String alias) {
        return alias != null
             ? new TableWrapperImpl(thisalias)
             : this ;
    }
New to GrepCode? Check out our FAQ X