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 org.ujorm.Key;
 import org.ujorm.Ujo;
Database column meta-data

Author(s):
Pavel Ponec
Composed:
1 - * DbType
 
 public final class MetaColumn extends MetaRelation2Many implements ColumnWrapper {
     private static final Class<MetaColumnCLASS = MetaColumn.class;

    
A constant for an auto index name
 
     public static final String AUTO_INDEX_NAME = "AUTO";

    
Property Factory
 
     private static final KeyFactory<MetaColumnfa = KeyFactory.CamelBuilder.get();
    
DB primary key
 
     public static final Key<MetaColumn,BooleanPRIMARY_KEY = .newKey("primaryKey"false);
    
Database Type
 
     public static final Key<MetaColumn,DbTypeDB_TYPE = .newKey("dbType".);
    
Column NOT-NULL
 
     public static final Key<MetaColumn,BooleanMANDATORY = .newKey("mandatory"false);
    
Column value length
 
     public static final Key<MetaColumn,IntegerMAX_LENGTH = .newKey("maxLength", -1);
    
Column value precision
 
     public static final Key<MetaColumn,IntegerPRECISION = .newKey("precision", -1);
    
DB Default value
 
     public static final Key<MetaColumn,StringDEFAULT_VALUE = .newKey("default""");
    
A name of the non-unique database index for the column, where the same index can contain more columns. If the name is "AUTO" then automatic name based on column setting is generated. If a single column of the index is marked as unique, so the entire index will be unique.
 
     public static final Key<MetaColumn,StringINDEX = .newKey("index""");
    
A name of the unique database index for the column, where the same index can contain more columns. If the name is "AUTO" then automatic name based on column setting is generated. If a single column of the index is marked as unique, so the entire index will be unique.
 
     public static final Key<MetaColumn,StringUNIQUE_INDEX = .newKey("uniqueIndex""");
    
A name of the constraint for the case a foreign key
 
     public static final Key<MetaColumn,StringCONSTRAINT_NAME = .newKey("constraintName""");
    
Convert, save and read application data from/to the database
 
     public static final Key<MetaColumn,Class<? extends ITypeService>> CONVERTER = .newClassKey("converter"ITypeService.class);
    
Comment of the database column
 
     public static final Key<MetaColumn,StringCOMMENT = .newKey("comment".);
    
The key initialization
 
     static{.lock();}

    
If current column is a foreign key than related model is a related table column (primarky key by default).
 
     private List<MetaColumnrelatedModel;
    
Foreign column names.
 
     private String[] foreignNames = null;
     private static final String[] EMPTY_NAMES = new String[0];
    
A Java Type Code to a quick JDBC management.

 
     private char typeCode;
     private boolean foreignKey;
    
Type converter. Value is Notnull always.
 
     private final ITypeService converter;
    public MetaColumn() {
        this(null);
    }
    public MetaColumn(ITypeService converter) {
        this. = converter;
    }
    @SuppressWarnings({"LeakingThisInConstructor""unchecked"})
    public MetaColumn(MetaTable tableKey tablePropertyMetaColumn param) {
        super(tabletablePropertyparam);
        this. = isTypeOf(OrmUjo.class);
        Field field = UjoManager.getInstance().getPropertyField(table.getType(), tableProperty);
        Column column = field!=null ? field.getAnnotation(Column.class) : null;
        if (param!=null) {
            changeDefault(this.of(param));
            changeDefault(this  , .of(param));
            changeDefault(this , .of(param));
            changeDefault(this  , .of(param));
            changeDefault(this    , .of(param));
            changeDefault(this      , .of(param));
            changeDefault(this,.of(param));
            changeDefault(this    , .of(param));
            changeDefault(this  , .of(param));
        }
        if (column!=null) {
            changeDefault(thiscolumn.pk());
            changeDefault(this  , column.mandatory());
            changeDefault(this , column.length());
            changeDefault(this  , column.precision());
            changeDefault(this    , column.type());
            changeDefault(this      , column.index());
            changeDefault(this,column.uniqueIndex());
            changeDefault(thiscolumn.constraintName());
            changeDefault(this  , column.converter());
        }
        final Validator validator = tableProperty.getValidator();
        if (validator != null) {
            changeDefault(this , ValidatorUtils.isMandatoryValidator(validator));
            changeDefault(this, ValidatorUtils.getMaxLength(validator));
        }
        // Assign Comments:
        if (field != null) {
            final Comment comment = field.getAnnotation(Comment.class);
            if (comment != null) {
                changeDefault(this  , comment.value());
            }
        }
        // Assign the Converter:
        final Class converterType = .isDefault(this) ? null : .of(this);
         = getHandler().getParameters().getConverter(converterType);
        // DB Type must be assigned after to create the converter instance:
        if (.isDefault(this)) {
            ..of(table).changeDbType(this);
        }
        // The MAX_LENGTH must be after the DB_TYPE:
        if (.isDefault(this)) {
            ..of(table).changeDbLength(this);
        }
    }

    
It is a DB column (either a value of a foreign key), not a relation to many.
    @Override
    public boolean isColumn() {
        return true;
    }

    
Is it a Foreign Key ?
    @Override
    public boolean isForeignKey() {
        return ;
    }

    
Is it a Primary Key?
    public boolean isPrimaryKey() {
        final boolean result = .of(this);
        return result;
    }

    
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);
    }

    
Returns a maximal db column length in the database.

Returns:
If key is undefined then the method returns value -1.
    public int getMaxLength() {
        return .of(this);
    }

    
Returns the db column precision.

Returns:
If key is undefined then the method returns value -1.
    public int getPrecision() {
        return .of(this);
    }

    
Returns true if the related db column is NOT NULL.
    public boolean isMandatory() {
        return .of(this);
    }

    
Returns an original foreign columns in case a foreign column.
    public MetaTable getForeignTable() {
        return getForeignColumns().get(0).getTable();
    }

    
Returns an original foreign columns in case a foreign column.
    @SuppressWarnings("unchecked")
    public List<MetaColumngetForeignColumns() {
        if (==null) {
             = createForeignColumns();
        }
        return ;
    }

    
Returns an original foreign columns in case a foreign column.

Returns:
Returns an original foreign columns in case a foreign column.
Throws:
java.lang.IllegalStateException The relation column have no foreign keys!
    @SuppressWarnings("unchecked")
        List<MetaColumnresult;
        MetaTable table;
        if (.of(thisinstanceof RelationToOne) {
            RelationToOne rto = (RelationToOne.of(this);
            MetaColumn mc = (MetaColumngetHandler().findColumnModel(rto.getRelatedKey(), true);
            result = new ArrayList<MetaColumn>(1);
            result.add(mc);
        } else {
            table = getHandler().findTableModel(getType());
            if (table!=null) {
                MetaPKey pk = ..of(table);
                result = ..getList(pk);
            } else {
                result = Collections.emptyList();
            }
        }
        if (result.isEmpty()) {
            throw new IllegalStateException("The relation column " + this + " have no foreign keys!");
        }
        return result;
    }

    
Returns names of foreign columns.
TODO: Is a time to an optimization ?
    @SuppressWarnings("unchecked")
    private String[] getForeignColumnNames() {
        if (==null) {
            if (isForeignKey()) {
                List<MetaColumndbColumns = getForeignColumns();
                final StringTokenizer tokenizer = new StringTokenizer(dbColumns.size()==1
                        ? getName() : """, ");
                ArrayList<StringfNames = new ArrayList<String>(dbColumns.size());
                for (MetaColumn dbColumn : dbColumns) {
                    String name;
                    if (tokenizer.hasMoreTokens()) {
                        name = tokenizer.nextToken();
                    } else {
                        name = "fk_"
                          // + MetaTable.NAME.of(foreignTable)
                             + ..of(this)
                             + "_"
                             + ..of(dbColumn)
                             ;
                    }
                    fNames.add(name);
                }
                 = fNames.toArray(new String[fNames.size()]);
            } else {
                 = ;
            }
        }
        return ;
    }

    
Returns a name of foreign column by index
    public String getForeignColumnName(int index) {
        final String result = getForeignColumnNames()[index];
        return result;
    }

    
Returns a key value from a table
    @SuppressWarnings("unchecked")
    public Object getValue(final OrmUjo bo) {
        final Key key = super.getKey();
        final Object result = key.of(bo);
        return result;
    }

    
Returns a key value from a table

Parameters:
ujo Related Ujo object
value A value to assign.
    @SuppressWarnings("unchecked")
    public void setValue(final Ujo boObject value) {
        final Key key = super.getKey();
        if (isForeignKey()
        &&   value !=null
        && !(value instanceof OrmUjo)) {
             value = new ForeignKey(value);
        }
        key.setValue(bovalue);
    }

    
Returns a Java Class of value
    public Class getType() {
        return .of(this).getType();
    }

    
Returns a column name
    public final String getName() {
        return .of(this);
    }

    
Returns a DB, TABLE and COLUMN name
    public String getFullName() {
        try {
            StringBuilder out = new StringBuilder(32);
            MetaTable table = .of(this);
            table.getDatabase()
                .getDialect()
                .printFullTableName(tableout);
            out.append('.');
            out.append(getName());
            return out.toString();
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    
Returns a full SQL column alias name by sample: "TABLE_ALIAS"."ORIG_COLUMN"
    public String getColumnAlias() {
        try {
            final String result = .of(this)
                .getDatabase()
                .getDialect()
                .printColumnAlias(thisnew StringBuilder(32))
                .toString();
            return result;
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    
Print a full 'alias' name of foreign column by index
    public void printForeignColumnFullName(int indexAppendable outthrows IOException {
        SqlDialect dialect = .of(this)
                .getDatabase()
                .getDialect();
        dialect.printQuotedName(getTableAlias(), out);
        out.append('.');
        dialect.printQuotedName(getForeignColumnNames()[index], out);
    }

    
A TypeCode

    public char getTypeCode() {
        return ;
    }

    
Has the key a default value (not null) ? If the default value is an empty String than method returns false.
    public boolean hasDefaultValue() {
        final Object value = super.getKey().getDefault();
        boolean result = value instanceof String
            ?  ((String)value).length()>0
            : value!=null
            ;
        return result;
    }

    
Returns a default value in a JDBC friendly type. The real result type depends in an implementatin of the ITypeService. For example a Java Enumerator default value can return either the Integer or String type too.

        final Object result = new UjoStatement().getDefaultValue(this);
        return result;
    }

    
Returns a SQL dialect class from a related Database
    public Class getDialectClass() {
         final Class result = ..of(this).getDatabase().get(.);
         return result;
    }

    
Returns a SQL dialect class from a related Database
    public String getDialectName() {
         return getDialectClass().getSimpleName();
    }

    
Initialize a type code - for an internal use only.
    public void initTypeCode() {
        // Test for a read-only state:
        checkReadOnly(true);
        // Assign the Type code:
         = TypeService.getTypeCode(this);
        // Modify a relation type:
        if (isForeignKey()) {
            List<MetaColumncols = getForeignColumns();
            if (cols.size()>0) {
                .setValue(this.of(cols.get(0)));
            }
        }
    }

    
Is the related key type void?
    public boolean isVoid() {
        return isTypeOf(Void.class);
    }

    
Returns a constraint name for case a foreigh key
    public String getConstraintName() {
        return .of(this);
    }

    
Returna not null converter
    public ITypeService getConverter() {
        return ;
    }
    
Returns a native database code for a DDL statements
    public Class getDbTypeClass() {
        if (!readOnly()) {
            if (isForeignKey()) {
                // The foreign type is not initialized correctly yet.
                return getType();
            } else {
                this.initTypeCode();
            }
        }
        return .getDbTypeClass(this);
    }

    
Get link to a column meta-model
    @Override
    public MetaColumn getModel() {
        return this;
    }

    
Create new object column for the new alias

Parameters:
alias Nullable alias value
Returns:
New instance of ColumnWrapper for a different alias.
    public final ColumnWrapper addTableAlias(final String alias) {
        return alias != null
             ? new ColumnWrapperImpl(thisalias)
             : this ;
    }
New to GrepCode? Check out our FAQ X