Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright 2011 Vecna Technologies, Inc. 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 com.vecna.dbDiff.hibernate;
 
 import java.sql.Types;
 import java.util.List;
 
 
Creates DbDiff relational database model from Hibernate mappings

Author(s):
ogolberg@vecna.com
 
 public class HibernateMappingsConverter {
   private static final String DEFAULT_KEY_SEQ = "1";
   private static final String POSTGRE_SQL = "PostgreSQL";
 
   private static final ImmutableSet<IntegerNUMERIC_TYPES = ImmutableSet.of(
                                                                              .,
                                                                              .,
                                                                              .,
                                                                              .,
                                                                              .,
                                                                              .,
                                                                              .,
                                                                              .,
                                                                              .,
                                                                              .,
                                                                              .
       );
 
   private final CatalogSchema m_catalogSchema;

  
Create a new converter instance

Parameters:
catalogSchema default catalog/schema information
 
   public HibernateMappingsConverter(CatalogSchema catalogSchema) {
      = catalogSchema;
   }
 
   private Dialect getDialect(Configuration hibernateConfiguration) {
     String dialectClassName = hibernateConfiguration.getProperty("hibernate.dialect");
     if (dialectClassName == null) {
       throw new IllegalStateException("dialect is not set");
     }
     Class<?> dialectClass;
 
     try {
       dialectClass = Thread.currentThread().getContextClassLoader().loadClass(dialectClassName);
     } catch (ClassNotFoundException e) {
       throw new IllegalStateException("can't load dialect class"e);
     }
 
     try {
       return (DialectdialectClass.newInstance();
     } catch (IllegalAccessException e) {
       throw new IllegalStateException("can't create dialect"e);
     } catch (InstantiationException e) {
       throw new IllegalStateException("can't create dialect"e);
     }
   }

  
Convert Hibernate mappings to DbDiff RelationalDatabase

Parameters:
hibernateConfiguration hibernate configuration
mapping hibernate mapping
Returns:
a RelationalDatabase
Throws:
com.vecna.dbDiff.model.relationalDb.RelationalValidationException if resulting relational database model is invalid
  public RelationalDatabase convert(Configuration hibernateConfigurationMapping mappingthrows RelationalValidationException {
    List<RelationalTabletables = new ArrayList<RelationalTable>();
    @SuppressWarnings("unchecked")
    Iterator<org.hibernate.mapping.TablemappedTables = hibernateConfiguration.getTableMappings();
    Dialect dialect = getDialect(hibernateConfiguration);
    HibernateSqlTypeMapper dataTypeMapper = createHibernateSqlTypeMapper(hibernateConfiguration);
    while (mappedTables.hasNext()) {
      tables.add(convertTable(mappedTables.next(), dialectdataTypeMappermapping));
    }
    RelationalDatabase rdb = new RelationalDatabase();
    rdb.setTables(tables);
    return rdb;
  }

  
Creates an instance of HibernateSqlTypeMapper if it is defined. Otherwise it returns null.

Parameters:
hibernateConfiguration
Returns:
null or an instance of HibernateSqlTypeMapper
  private HibernateSqlTypeMapper createHibernateSqlTypeMapper(Configuration hibernateConfiguration) {
    Dialect dialect = getDialect(hibernateConfiguration);
    String simpleName = dialect.getClass().getSimpleName();
    boolean isPostgreSQL =  StringUtils.startsWithIgnoreCase(simpleName);
    return isPostgreSQL ? new PostgreSqlTypeMapper() : null;
  }
  private RelationalTable convertTable(org.hibernate.mapping.Table mappedTableDialect dialect,
                                       HibernateSqlTypeMapper dataTypeMapperMapping mapping)
                                           throws RelationalValidationException {
    RelationalTable table = new RelationalTable();
    Table tableTable = new Table();
    tableTable.setName(StringUtils.lowerCase(mappedTable.getName()));
    tableTable.setSchema(.getSchema());
    table.setTable(tableTable);
    List<Columncolumns = Lists.newArrayList();
    List<RelationalIndexindices = Lists.newArrayList();
    @SuppressWarnings("unchecked")
    Iterator<org.hibernate.mapping.ColumnmappedColumns = mappedTable.getColumnIterator();
    int idx = 1;
    while (mappedColumns.hasNext()) {
      org.hibernate.mapping.Column mappedColumn = mappedColumns.next();
      Column column = convertColumn(mappedColumnmappedTableidx++, dialectdataTypeMappermapping);
      columns.add(column);
      if (mappedColumn.isUnique()) {
        indices.add(getUniqueIndex(tablecolumn));
      }
    }
    table.setColumns(columns);
    List<ForeignKeyfkeys = new ArrayList<ForeignKey>();
    @SuppressWarnings("unchecked")
    Iterator<org.hibernate.mapping.ForeignKeymappedKeys = mappedTable.getForeignKeyIterator();
    while (mappedKeys.hasNext()) {
      ForeignKey fkey = convertForeignKey(mappedKeys.next());
      if (fkey != null) {
        fkeys.add(fkey);
      }
    }
    table.setFks(fkeys);
    @SuppressWarnings("unchecked")
    Iterator<IndexmappedIndices = mappedTable.getIndexIterator();
    while (mappedIndices.hasNext()) {
      indices.add(convertIndex(mappedIndices.next(), table));
    }
    @SuppressWarnings("unchecked")
    Iterator<UniqueKeymappedUniqueKeys = mappedTable.getUniqueKeyIterator();
    while (mappedUniqueKeys.hasNext()) {
      indices.add(convertIndex(mappedUniqueKeys.next(), table));
    }
    if (mappedTable.getPrimaryKey() != null) {
      indices.add(convertIndex(mappedTable.getPrimaryKey(), table));
      List<StringpkColumnNames = Lists.newArrayList();
      @SuppressWarnings("unchecked")
      Iterator<org.hibernate.mapping.ColumnpkColumns = mappedTable.getPrimaryKey().getColumnIterator();
      while (pkColumns.hasNext()) {
        pkColumnNames.add(pkColumns.next().getName().toLowerCase());
      }
      table.setPkColumns(pkColumnNames);
    }
    table.setIndices(indices);
    return table;
  }
    RelationalIndex index = new RelationalIndex();
    Table tableDef = new Table();
    tableDef.setCatalog(table.getTable().getCatalog());
    tableDef.setSchema(table.getTable().getSchema());
    index.setTable(tableDef);
    index.setColumns(new ArrayList<Column>(Collections.singletonList(column)));
    return index;
  }
  private RelationalIndex convertIndex(Constraint mappedConstraintRelationalTable table)
      throws RelationalValidationException {
    @SuppressWarnings("unchecked")
    Iterator<org.hibernate.mapping.ColumnmappedColumns = mappedConstraint.getColumnIterator();
    return convertIndex(nullmappedColumnstable);
  }
  private RelationalIndex convertIndex(Index mappedIndexRelationalTable table)
      throws RelationalValidationException {
    @SuppressWarnings("unchecked")
    Iterator<org.hibernate.mapping.ColumnmappedColumns = mappedIndex.getColumnIterator();
    return convertIndex(StringUtils.lowerCase(mappedIndex.getName()), mappedColumnstable);
  }
  private RelationalIndex convertIndex(String nameIterator<org.hibernate.mapping.ColumnmappedColumnsRelationalTable table)
      throws RelationalValidationException {
    List<Columncolumns = new ArrayList<Column>();
    while (mappedColumns.hasNext()) {
      columns.add(table.getColumnByName(mappedColumns.next().getName().toLowerCase()));
    }
    RelationalIndex index = new RelationalIndex();
    Table indexTable = new Table();
    indexTable.setName(name);
    indexTable.setSchema(.getSchema());
    index.setTable(indexTable);
    index.setColumns(columns);
    return index;
  }
    org.hibernate.mapping.Column column = mappedKey.getColumn(0);
    org.hibernate.mapping.Table table = mappedKey.getTable();
    org.hibernate.mapping.Table referencedTable = mappedKey.getReferencedTable();
    org.hibernate.mapping.Column referencedColumn;
    if (mappedKey.getReferencedColumns().size() == 0) {
      referencedColumn = referencedTable.getPrimaryKey().getColumn(0);
    } else {
      referencedColumn = (org.hibernate.mapping.ColumnmappedKey.getReferencedColumns().get(0);
    }
    ForeignKey fkey = new ForeignKey();
    fkey.setFkCatalog(StringUtils.lowerCase(table.getCatalog()));
    fkey.setFkColumn(column.getName().toLowerCase());
    fkey.setFkName(mappedKey.getName().toLowerCase());
    fkey.setFkTable(table.getName().toLowerCase());
    fkey.setPkCatalog(StringUtils.lowerCase(referencedTable.getCatalog()));
    fkey.setPkColumn(referencedColumn.getName().toLowerCase());
    fkey.setPkTable(referencedTable.getName().toLowerCase());
    return fkey;
  }
                               int ordinalDialect dialectHibernateSqlTypeMapper dataTypeMapperMapping mapping) {
    Column column = new Column();
    ColumnType type = new ColumnType(mappedColumn.getSqlTypeCode(mapping), mappedColumn.getSqlType(dialectmapping));
    column.setColumnType(type);
    if (dataTypeMapper != null) {
      dataTypeMapper.mapType(column);
    }
    if (.contains(column.getType())) {
      if (mappedColumn.getPrecision() != ....) {
        column.setColumnSize(mappedColumn.getPrecision());
      }
    } else if ("character".equals(mappedColumn.getValue().getType().getName())) {
      column.setColumnSize(1);
    } else if (!"binary".equals(mappedColumn.getValue().getType().getName())
        && mappedColumn.getLength() != ....) {
      column.setColumnSize(mappedColumn.getLength());
    }
    column.setDefault(mappedColumn.getDefaultValue());
    column.setName(mappedColumn.getName().toLowerCase());
    boolean notNull = !mappedColumn.isNullable()
        || (owner.getPrimaryKey() != null && owner.getPrimaryKey().getColumns().contains(mappedColumn));
    column.setIsNullable(!notNull);
    column.setCatalog(StringUtils.lowerCase(owner.getCatalog()));
    column.setSchema(StringUtils.lowerCase(owner.getSchema()));
    column.setOrdinal(ordinal);
    column.setTable(owner.getName().toLowerCase());
    column.setDefault(mappedColumn.getDefaultValue());
    return column;
  }
New to GrepCode? Check out our FAQ X