Example usage for org.hibernate MappingException MappingException

List of usage examples for org.hibernate MappingException MappingException

Introduction

In this page you can find the example usage for org.hibernate MappingException MappingException.

Prototype

public MappingException(String message) 

Source Link

Document

Constructs a MappingException using the given information.

Usage

From source file:gov.nih.nci.iso21090.hibernate.usertype.EnumUserType.java

License:BSD License

/**
 * @param params Properties object containing enumClassName property
 *///from www.  j  a  v a2  s .  co m
public void setParameterValues(Properties params) {
    String enumClassName = params.getProperty("enumClassName");
    if (enumClassName == null) {
        throw new MappingException("enumClassName parameter not specified");
    }

    try {
        this.clazz = Class.forName(enumClassName);
    } catch (java.lang.ClassNotFoundException e) {
        throw new MappingException("enumClass " + enumClassName + " not found", e);
    }
}

From source file:net.sourceforge.squirrel_sql.plugins.dbcopy.CopyExecutor.java

License:Open Source License

/**
 * Sorts the specified destInfos array based on the order of the sourceInfos
 * array.  Not a very efficient algorthim, but it gets the job done.
 * TODO: rewrite this using Collections sorting capability.
 * /*w w w  .  j  av a  2  s.c  o m*/
 * @param sourceInfos
 * @param destInfos
 * @param sourceTableName
 * @param destTableName
 * @return a re-ordered version of the specified destInfos array
 * @throws MappingException if the arrays differ in length or column names.
 */
private TableColumnInfo[] sort(TableColumnInfo[] sourceInfos, TableColumnInfo[] destInfos,
        String sourceTableName, String destTableName) throws MappingException {
    if (sourceInfos.length != destInfos.length) {
        //i18n[CopyExecutor.tablecolmismatch=Column count for table {0} in 
        //source database is {1}, but column count for table {2} in 
        //destination database is {3}
        String msg = getMessage("CopyExecutor.tablecolmismatch", new Object[] { sourceTableName,
                Integer.valueOf(sourceInfos.length), destTableName, Integer.valueOf(destInfos.length) });
        throw new MappingException(msg);
    }
    ArrayList<TableColumnInfo> result = new ArrayList<TableColumnInfo>();

    for (int sourceIdx = 0; sourceIdx < sourceInfos.length; sourceIdx++) {
        TableColumnInfo sourceInfo = sourceInfos[sourceIdx];
        // trim the column name in case of HADB
        String sourceColumnName = sourceInfo.getColumnName().trim();
        boolean found = false;
        int destIdx = 0;
        while (!found && destIdx < destInfos.length) {
            TableColumnInfo destInfo = destInfos[destIdx];
            // trim the column name in case of HADB
            String destColumnName = destInfo.getColumnName().trim();
            if (destColumnName.equalsIgnoreCase(sourceColumnName)) {
                result.add(destInfo);
                found = true;
            }
            destIdx++;
        }
        if (!found) {
            throw new MappingException("Destination table " + destTableName
                    + " doesn't appear to have a column named " + sourceInfo.getColumnName());
        }
    }
    return result.toArray(new TableColumnInfo[destInfos.length]);
}

From source file:net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil.java

License:Open Source License

public static ITableInfo getTableInfo(ISession session, String schema, String tableName)
        throws SQLException, MappingException, UserCancelledOperationException {
    ISQLConnection con = session.getSQLConnection();
    // Currently, as of milestone 3, Axion doesn't support "schemas" like
    // other databases. So, set the schema to emtpy string if we detect
    // an Axion session.
    if (con.getSQLMetaData().getDriverName().toLowerCase().startsWith("axion")) {
        schema = "";
    }//from  w  w  w .  java2s . c  om
    String catalog = null;
    // MySQL uses catalogs and not schemas
    if (DialectFactory.isMySQL(session.getMetaData())) {
        catalog = schema;
        schema = null;
    }
    // trim the table name in case of HADB
    tableName = tableName.trim();
    ITableInfo[] tis = getTables(session, catalog, schema, tableName);
    if (tis == null || tis.length == 0) {
        if (Character.isUpperCase(tableName.charAt(0))) {
            tableName = tableName.toLowerCase();
        } else {
            tableName = tableName.toUpperCase();
        }
        tis = getTables(session, null, schema, tableName);
        if (tis.length == 0) {
            if (Character.isUpperCase(tableName.charAt(0))) {
                tableName = tableName.toLowerCase();
            } else {
                tableName = tableName.toUpperCase();
            }
            tis = getTables(session, null, schema, tableName);
        }
    }
    if (tis.length == 0) {
        // i18n[DBUtil.error.tablenotfound=Couldn't locate table '{0}' in
        // schema '(1)']
        String msg = s_stringMgr.getString("DBUtil.error.tablenotfound", new String[] { tableName, schema });
        throw new MappingException(msg);
    }
    if (tis.length > 1) {
        if (log.isDebugEnabled()) {
            log.debug("DBUtil.getTableInfo: found " + tis.length + " that matched " + "catalog=" + catalog
                    + " schema=" + schema + " tableName=" + tableName);
        }
    }
    return tis[0];
}

From source file:net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil.java

License:Open Source License

/**
 * This will take into account any special needs that the destination session has with regard to user
 * preferences, and throw a MappingException if any user preference isn't valid for the specified
 * destination session./*w w  w .jav a  2 s. c  o m*/
 * 
 * @param destSession
 */
public static void sanityCheckPreferences(ISession destSession) throws MappingException {

    if (DialectFactory.isFirebird(destSession.getMetaData())) {
        if (!PreferencesManager.getPreferences().isCommitAfterTableDefs()) {
            // TODO: maybe instead of throwing an exception, we could ask
            // the user if they would like us to adjust their preference for
            // them.

            // i18n[DBUtil.error.firebirdcommit=Firebird requires commit
            // table create before inserting records. Please adjust your
            // preferences.]
            String msg = s_stringMgr.getString("DBUtil.error.firebirdcommit");
            throw new MappingException(msg);
        }
    }
}

From source file:net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil.java

License:Open Source License

public static String getCreateTableSql(SessionInfoProvider prov, ITableInfo ti, String destTableName,
        String destSchema, String destCatalog)
        throws SQLException, MappingException, UserCancelledOperationException {

    ISession sourceSession = prov.getSourceSession();
    String sourceSchema = prov.getSourceDatabaseObjects().get(0).getSchemaName();
    String sourceCatalog = prov.getSourceDatabaseObjects().get(0).getCatalogName();
    String sourceTableName = getQualifiedObjectName(sourceSession, sourceCatalog, sourceSchema,
            ti.getSimpleName(), DialectFactory.SOURCE_TYPE);
    ISession destSession = prov.getDestSession();
    //      String destSchema = getSchemaNameFromDbObject(prov.getDestDatabaseObject());
    //      String destCatalog = prov.getDestDatabaseObject().getCatalogName();
    String destinationTableName = getQualifiedObjectName(destSession, destCatalog, destSchema, destTableName,
            DialectFactory.DEST_TYPE);/*from   w w  w. j a  va  2  s. co  m*/
    StringBuilder result = new StringBuilder("CREATE TABLE ");
    result.append(destinationTableName);
    result.append(" ( ");
    result.append("\n");
    TableColumnInfo colInfo = null;
    try {
        ISQLConnection sourceCon = prov.getSourceSession().getSQLConnection();
        TableColumnInfo[] colInfoArr = sourceCon.getSQLMetaData().getColumnInfo(ti);
        if (colInfoArr.length == 0) {
            // i18n[DBUtil.error.nocolumns=Table '{0}' in schema '{1}' has
            // no columns to copy]
            String msg = s_stringMgr.getString("DBUtil.error.nocolumns",
                    new String[] { ti.getSimpleName(), ti.getSchemaName() });
            throw new MappingException(msg);
        }
        for (int i = 0; i < colInfoArr.length; i++) {
            colInfo = colInfoArr[i];
            result.append("\t");
            String columnSql = DBUtil.getColumnSql(prov, colInfo, sourceTableName, destinationTableName);
            result.append(columnSql);
            if (i < colInfoArr.length - 1) {
                result.append(",\n");
            }
        }

        // If the user wants the primary key copied and the source session
        // isn't Axion (Axion throws SQLException for getPrimaryKeys())

        // TODO: Perhaps we can tell the user when they click "Copy Table"
        // if the source session is Axion and they want primary keys that
        // it's not possible.
        if (_prefs.isCopyPrimaryKeys() && !DialectFactory.isAxion(sourceSession.getMetaData())) {
            String pkString = DBUtil.getPKColumnString(sourceCon, ti);
            if (pkString != null) {
                result.append(",\n\tPRIMARY KEY ");
                result.append(pkString);
            }
        }
        result.append(")");
    } catch (MappingException e) {
        if (colInfo != null) {
            // i18n[DBUtil.error.maptype=Couldn't map type for table='{0}'
            // column='{1}']
            String msg = s_stringMgr.getString("DBUtil.error.maptype",
                    new String[] { destinationTableName, colInfo.getColumnName() });
            log.error(msg, e);
        }
        throw e;
    }

    return result.toString();
}

From source file:net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil.java

License:Open Source License

/**
 * Checks the specified column is not a keyword in the specified session.
 * //from  w ww  .  j a  v a 2 s .  co m
 * @param session
 *        the session whose keywords to check against
 * @param table
 *        the name of the table to use in the error message
 * @param column
 *        the name of the column to check
 * 
 * @throws MappingException
 *         if the specified column is a keyword in the specified session
 */
public static void checkKeyword(ISession session, String table, String column) throws MappingException {
    if (isKeyword(session, column)) {
        String message = getMessage("DBUtil.mappingErrorKeyword", new String[] { table, column });
        throw new MappingException(message);
    }
}

From source file:net.sourceforge.squirrel_sql.plugins.dbcopy.util.DBUtil.java

License:Open Source License

public static void validateColumnNames(ITableInfo ti, SessionInfoProvider prov)
        throws MappingException, UserCancelledOperationException {
    if (prov == null) {
        return;// w ww  .  j  av a 2 s.  c o  m
    }
    ISession sourceSession = prov.getSourceSession();
    ISession destSession = prov.getDestSession();
    if (sourceSession == null || destSession == null) {
        return;
    }
    ISQLConnection sourceCon = sourceSession.getSQLConnection();
    ISQLConnection con = destSession.getSQLConnection();
    TableColumnInfo[] colInfoArr = null;
    try {
        colInfoArr = sourceCon.getSQLMetaData().getColumnInfo(ti);
    } catch (SQLException e) {
        // ignore any SQLExceptions. This would only if we could not get
        // column info from the SQL database meta data.
        return;
    }
    for (int colIdx = 0; colIdx < colInfoArr.length; colIdx++) {
        TableColumnInfo colInfo = colInfoArr[colIdx];
        IDatabaseObjectInfo selectedDestObj = prov.getDestDatabaseObject();
        String schema = selectedDestObj.getSimpleName();
        String catalog = selectedDestObj.getCatalogName();
        String tableName = getQualifiedObjectName(destSession, catalog, schema, TEST_TABLE_NAME,
                DialectFactory.DEST_TYPE);

        StringBuilder sql = new StringBuilder("CREATE TABLE ");
        sql.append(tableName);
        sql.append(" ( ");
        sql.append(colInfo.getColumnName());
        sql.append(" CHAR(10) )");
        boolean cascade = DialectFactory.isFrontBase(destSession.getMetaData());
        try {
            dropTable(TEST_TABLE_NAME, schema, catalog, destSession, cascade, DialectFactory.DEST_TYPE);
            DBUtil.executeUpdate(con, sql.toString(), false);
        } catch (SQLException e) {
            String message = getMessage("DBUtil.mappingErrorKeyword",
                    new String[] { ti.getSimpleName(), colInfo.getColumnName() });
            log.error(message, e);
            throw new MappingException(message);
        } finally {
            dropTable(tableName, schema, catalog, destSession, cascade, DialectFactory.DEST_TYPE);
        }

    }
}

From source file:nl.strohalm.cyclos.utils.hibernate.AbstractEnumType.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public void setParameterValues(final Properties params) {
    // Read the enum class name from the parameters
    final String enumClassName = params.getProperty("enumClassName");
    if (enumClassName == null) {
        throw new MappingException("enumClassName parameter not specified");
    }// w  w  w  .j ava 2 s  . c o m

    Class clazz;
    try {
        clazz = Class.forName(enumClassName);
    } catch (final java.lang.ClassNotFoundException e) {
        throw new MappingException("enumClass " + enumClassName + " not found", e);
    }

    if (Enum.class.isAssignableFrom(clazz)) {
        this.enumType = clazz;
    } else {
        throw new MappingException("enumClass " + enumClassName + " is not an enumeration");
    }

    try {
        final Method values = this.enumType.getMethod("values");
        this.enumValues = (EnumType[]) values.invoke(null);
    } catch (final Exception e) {
        throw new MappingException("enumClass " + enumClassName + " does not have the values() method");
    }
}

From source file:org.babyfish.hibernate.cfg.Configuration.java

License:Open Source License

private void processPersistentClasses() {
    Iterator<PersistentClass> classMappings = this.getClassMappings();
    while (classMappings.hasNext()) { //TODO: please iterate its subclasses.
        PersistentClass persistentClass = classMappings.next();
        Class<?> mappedClass = persistentClass.getMappedClass();
        ObjectModelFactoryProvider provider = Metadatas.getObjectModelFactoryProvider(mappedClass);
        if (provider == null) {
            if (mappedClass.isAnnotationPresent(JPAObjectModelInstrument.class)) {
                throw new IllegalProgramException(LAZY_RESOURCE.get().missInstrument(mappedClass,
                        JPAObjectModelInstrument.class, INSTRUMENT_EXPECTED_POM_SECTION));
            }//from  w w w .  j  ava  2 s.co m
        } else {
            if (!(provider instanceof HibernateObjectModelFactoryProvider)) {
                throw new IllegalProgramException(
                        LAZY_RESOURCE.get().requiredHibernateObjectModelFactoryProvider(mappedClass,
                                HibernateObjectModelFactoryProvider.class));
            }
            HibernateObjectModelMetadata metadata = HibernateMetadatas.of(mappedClass);
            for (org.babyfish.model.metadata.Property property : metadata.getDeclaredProperties().values()) {
                JPAProperty jpaProperty = (JPAProperty) property;
                if (jpaProperty instanceof AssociationProperty) {
                    AssociationProperty associationProperty = (AssociationProperty) jpaProperty;
                    if (associationProperty.getCovarianceProperty() != null) {
                        continue;
                    }
                }
                PropertyInfo ownerProperty = jpaProperty.getOwnerProperty();
                if (ownerProperty == null) {
                    continue;
                }
                Property mappingProperty = persistentClass.getProperty(ownerProperty.getName());
                mappingProperty.setPropertyAccessorName(EntityPropertyAccessor.class.getName());
                Value value = mappingProperty.getValue();
                if (property instanceof AssociationProperty) {
                    JPAAssociationProperty jpaAssociationProperty = (JPAAssociationProperty) property;
                    Class<?> standardReturnType = jpaAssociationProperty.getStandardReturnClass();
                    /*
                     * (1) Don't use jpaAssocationProperty.getHibernateProperty().
                     * This is org.hiberante.mapping.Property, that is org.hibernate.tuple.Property
                     * 
                     * (2) Don't invoke property.getType() or property.getValue().getType()
                     * that will cause the creating of original collection-type before the replacement.
                     */
                    if (jpaAssociationProperty.getCovarianceProperty() == null) {
                        if (standardReturnType == NavigableMap.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Map.class,
                                    MANavigableMapType.class);
                        } else if (standardReturnType == XOrderedMap.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Map.class,
                                    MAOrderedMapType.class);
                        } else if (standardReturnType == Map.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Map.class,
                                    MAOrderedMapType.class);
                        } else if (standardReturnType == NavigableSet.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Set.class,
                                    MANavigableSetType.class);
                        } else if (standardReturnType == XOrderedSet.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Set.class,
                                    MAOrderedSetType.class);
                        } else if (standardReturnType == Set.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Set.class,
                                    MAOrderedSetType.class);
                        } else if (standardReturnType == List.class) {
                            if (org.hibernate.mapping.Bag.class
                                    .isAssignableFrom(mappingProperty.getValue().getClass())) {
                                throw new MappingException(
                                        "In ObjectModel4ORM, Bag proeprty must be declared as java.util.Collection(not java.util.List)");
                            }
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.List.class,
                                    MAListType.class);
                        }
                        if (standardReturnType == Collection.class) {
                            replaceUserCollectionType(mappingProperty, org.hibernate.mapping.Bag.class,
                                    MAOrderedSetType.class);
                        }
                        if (value instanceof org.hibernate.mapping.Collection) {
                            org.hibernate.mapping.Collection collection = (org.hibernate.mapping.Collection) value;
                            collection.setTypeParameters(new MACollectionProperties(jpaAssociationProperty,
                                    collection.getTypeParameters()));
                        }

                        if (jpaAssociationProperty.getOwnerIndexProperty() != null) {
                            persistentClass
                                    .getProperty(jpaAssociationProperty.getOwnerIndexProperty().getName())
                                    .setPropertyAccessorName(EntityPropertyAccessor.class.getName());
                        }
                        if (jpaAssociationProperty.getOwnerKeyProperty() != null) {
                            persistentClass.getProperty(jpaAssociationProperty.getOwnerKeyProperty().getName())
                                    .setPropertyAccessorName(EntityPropertyAccessor.class.getName());
                        }
                    }
                }
            }
        }
    }
}

From source file:org.babyfish.hibernate.cfg.Configuration.java

License:Open Source License

private static void replaceUserCollectionType(Property mappingProperty,
        Class<? extends org.hibernate.mapping.Collection> hibernateCollectionType,
        Class<? extends AbstractMACollectionType> babyfishCollectionType) {
    /*//  w w w.  jav  a2  s. co  m
     * Don't invoke property.getType() or property.getValue().getType()
     * that will cause the creating of original collection-type before the replacement.
     * that is is slow
     */
    Value value = mappingProperty.getValue();
    if (!(value instanceof org.hibernate.mapping.Collection)) {
        throw new MappingException('"' + mappingProperty.getPersistentClass().getEntityName() + '.'
                + mappingProperty.getName() + "\" must be mapped as collection.");
    }
    org.hibernate.mapping.Collection collection = (org.hibernate.mapping.Collection) value;
    String typeName = collection.getTypeName();
    if (typeName == null) {
        if (!hibernateCollectionType.isAssignableFrom(value.getClass())) {
            throw new MappingException('"' + mappingProperty.getPersistentClass().getEntityName() + '.'
                    + mappingProperty.getName() + "\" must be mapped collection whose hibernate type is \""
                    + hibernateCollectionType.getName() + "\".");
        }
        collection.setTypeName(babyfishCollectionType.getName());
    } else {
        Class<?> userCollctionType;
        try {
            userCollctionType = ReflectHelper.classForName(typeName);
        } catch (ClassNotFoundException ex) {
            throw new MappingException(
                    '"' + mappingProperty.getPersistentClass().getEntityName() + '.' + mappingProperty.getName()
                            + "\" must be mapped as collection whose attribute \"collection-type\" is \""
                            + typeName + "\", but the there is no java type names\"" + typeName + "\".");
        }
        if (!babyfishCollectionType.isAssignableFrom(userCollctionType)) {
            throw new MappingException(
                    '"' + mappingProperty.getPersistentClass().getEntityName() + '.' + mappingProperty.getName()
                            + "\" must be mapped as collection whose attribut \"collection-type\" is \""
                            + typeName + "\", but the there class \"" + typeName + "\" is not \""
                            + babyfishCollectionType.getName() + "\" or its derived class.");
        }
    }
}