org.hibernate.engine.spi.Mapping - java examples

Here are the examples of the java api org.hibernate.engine.spi.Mapping taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

26 Examples 7

19 View Complete Implementation : DdlGenerator.java
Copyright GNU Lesser General Public License v3.0
Author : beangle
/**
 * @author chaostone
 * @version $Id: DdlGenerator.java Mar 22, 2012 9:45:57 AM chaostone $
 */
public clreplaced DdlGenerator {

    private Configuration configuration = null;

    private Dialect dialect;

    private List<String> tables = new ArrayList<String>(50);

    private List<String> sequences = new ArrayList<String>(50);

    private List<String> comments = new ArrayList<String>(50);

    private List<String> constraints = new ArrayList<String>(50);

    private List<String> indexes = new ArrayList<String>(50);

    private Messages messages;

    private String defaultCatalog;

    private String defaultSchema;

    private Mapping mapping;

    private Set<Table> processed = CollectUtils.newHashSet();

    private Map<String, List<List<String>>> files = CollectUtils.newHashMap();

    @SuppressWarnings("unchecked")
    public DdlGenerator(Dialect dialect, Locale locale) {
        super();
        this.dialect = dialect;
        this.messages = Messages.build(locale);
        files.put("1-tables.sql", Arrays.asList(tables, constraints, indexes));
        files.put("2-sequences.sql", Arrays.asList(sequences));
        files.put("3-comments.sql", Arrays.asList(comments));
    }

    /**
     * Generate sql scripts
     *
     * @param fileName
     * @param packageName
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public void gen(String fileName, String packageName) throws Exception {
        configuration = ConfigBuilder.build(new OverrideConfiguration());
        mapping = configuration.buildMapping();
        defaultCatalog = configuration.getProperties().getProperty(Environment.DEFAULT_CATALOG);
        defaultSchema = configuration.getProperties().getProperty(Environment.DEFAULT_SCHEMA);
        configuration.getProperties().put(Environment.DIALECT, dialect);
        // 1. first process clreplaced mapping
        Iterator<PersistentClreplaced> iterpc = configuration.getClreplacedMappings();
        while (iterpc.hasNext()) {
            PersistentClreplaced pc = iterpc.next();
            Clreplaced<?> clazz = pc.getMappedClreplaced();
            if (isNotBlank(packageName) && !clazz.getPackage().getName().startsWith(packageName))
                continue;
            // add comment to table and column
            pc.getTable().setComment(messages.get(clazz, clazz.getSimpleName()));
            commentProperty(clazz, pc.getTable(), pc.getIdentifierProperty());
            commentProperties(clazz, pc.getTable(), pc.getPropertyIterator());
            PersistentClreplaced mySuper = pc.getSuperclreplaced();
            while (null != mySuper) {
                commentProperties(clazz, pc.getTable(), mySuper.getPropertyIterator());
                mySuper = mySuper.getSuperclreplaced();
            }
            // generator sequence sql
            if (pc instanceof RootClreplaced) {
                IdentifierGenerator ig = pc.getIdentifier().createIdentifierGenerator(configuration.getIdentifierGeneratorFactory(), dialect, defaultCatalog, defaultSchema, (RootClreplaced) pc);
                if (ig instanceof PersistentIdentifierGenerator) {
                    String[] lines = ((PersistentIdentifierGenerator) ig).sqlCreateStrings(dialect);
                    sequences.addAll(Arrays.asList(lines));
                }
            }
            // generater table sql
            generateTableSql(pc.getTable());
        }
        // 2. process collection mapping
        Iterator<Collection> itercm = configuration.getCollectionMappings();
        while (itercm.hasNext()) {
            Collection col = itercm.next();
            if (isNotBlank(packageName) && !col.getRole().startsWith(packageName))
                continue;
            // collection sequences
            if (col.isIdentified()) {
                IdentifierGenerator ig = ((IdentifierCollection) col).getIdentifier().createIdentifierGenerator(configuration.getIdentifierGeneratorFactory(), dialect, defaultCatalog, defaultSchema, null);
                if (ig instanceof PersistentIdentifierGenerator) {
                    String[] lines = ((PersistentIdentifierGenerator) ig).sqlCreateStrings(dialect);
                    sequences.addAll(Arrays.asList(lines));
                }
            }
            // collection table
            if (!col.isOneToMany()) {
                Table table = col.getCollectionTable();
                String owner = col.getTable().getComment();
                Clreplaced<?> ownerClreplaced = col.getOwner().getMappedClreplaced();
                // resolved nested compoent name in collection's role
                String colName = substringAfter(col.getRole(), col.getOwnerEnreplacedyName() + ".");
                if (colName.contains("."))
                    ownerClreplaced = getPropertyType(col.getOwner(), substringBeforeLast(colName, "."));
                table.setComment(owner + "-" + messages.get(ownerClreplaced, substringAfterLast(col.getRole(), ".")));
                Column keyColumn = table.getColumn((Column) col.getKey().getColumnIterator().next());
                if (null != keyColumn)
                    keyColumn.setComment(owner + " ID");
                if (col instanceof IndexedCollection) {
                    IndexedCollection idxCol = (IndexedCollection) col;
                    Value idx = idxCol.getIndex();
                    if (idx instanceof ToOne)
                        commentToOne((ToOne) idx, (Column) idx.getColumnIterator().next());
                }
                if (col.getElement() instanceof ManyToOne) {
                    Column valueColumn = (Column) col.getElement().getColumnIterator().next();
                    commentToOne((ManyToOne) col.getElement(), valueColumn);
                } else if (col.getElement() instanceof Component) {
                    Component cp = (Component) col.getElement();
                    commentProperties(cp.getComponentClreplaced(), table, cp.getPropertyIterator());
                }
                generateTableSql(col.getCollectionTable());
            }
        }
        Set<String> commentSet = CollectUtils.newHashSet(comments);
        comments.clear();
        comments.addAll(commentSet);
        // 3. export to files
        for (String key : files.keySet()) {
            List<List<String>> sqls = files.get(key);
            FileWriter writer = new FileWriter(fileName + "/" + key, false);
            writes(writer, sqls);
            writer.flush();
            writer.close();
        }
    }

    /**
     * get component clreplaced by component property string
     *
     * @param pc
     * @param propertyString
     * @return
     */
    private Clreplaced<?> getPropertyType(PersistentClreplaced pc, String propertyString) {
        String[] properties = split(propertyString, '.');
        Property p = pc.getProperty(properties[0]);
        Component cp = ((Component) p.getValue());
        int i = 1;
        for (; i < properties.length; i++) {
            p = cp.getProperty(properties[i]);
            cp = ((Component) p.getValue());
        }
        return cp.getComponentClreplaced();
    }

    private void commentToOne(ToOne toOne, Column column) {
        String enreplacedyName = toOne.getReferencedEnreplacedyName();
        PersistentClreplaced referClreplaced = configuration.getClreplacedMapping(enreplacedyName);
        if (null != referClreplaced) {
            column.setComment(referClreplaced.getTable().getComment() + " ID");
        }
    }

    @SuppressWarnings("unchecked")
    private void commentProperty(Clreplaced<?> clazz, Table table, Property p) {
        if (null == p)
            return;
        if (p.getColumnSpan() == 1) {
            Column column = (Column) p.getColumnIterator().next();
            if (isForeignColumn(table, column)) {
                column.setComment(messages.get(clazz, p.getName()) + " ID");
            } else {
                column.setComment(messages.get(clazz, p.getName()));
            }
        } else if (p.getColumnSpan() > 1) {
            Component pc = ((Component) p.getValue());
            Clreplaced<?> columnOwnerClreplaced = pc.getComponentClreplaced();
            commentProperties(columnOwnerClreplaced, table, pc.getPropertyIterator());
        }
    }

    private void commentProperties(Clreplaced<?> clazz, Table table, Iterator<Property> ip) {
        while (ip.hasNext()) commentProperty(clazz, table, ip.next());
    }

    @SuppressWarnings("unchecked")
    private void generateTableSql(Table table) {
        if (!table.isPhysicalTable())
            return;
        Iterator<String> commenreplaceder = table.sqlCommentStrings(dialect, defaultCatalog, defaultSchema);
        while (commenreplaceder.hasNext()) {
            comments.add(commenreplaceder.next());
        }
        if (processed.contains(table))
            return;
        processed.add(table);
        tables.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
        Iterator<UniqueKey> subIter = table.getUniqueKeyIterator();
        while (subIter.hasNext()) {
            UniqueKey uk = subIter.next();
            String constraintString = uk.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema);
            if (constraintString != null)
                constraints.add(constraintString);
        }
        Iterator<Index> idxIter = table.getIndexIterator();
        while (idxIter.hasNext()) {
            final Index index = idxIter.next();
            indexes.add(index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
        }
        if (dialect.hasAlterTable()) {
            Iterator<ForeignKey> fkIter = table.getForeignKeyIterator();
            while (fkIter.hasNext()) {
                ForeignKey fk = fkIter.next();
                if (fk.isPhysicalConstraint()) {
                    constraints.add(fk.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    private boolean isForeignColumn(Table table, Column column) {
        Iterator<ForeignKey> fkIter = table.getForeignKeyIterator();
        while (fkIter.hasNext()) {
            ForeignKey fk = fkIter.next();
            if (fk.isPhysicalConstraint()) {
                if (fk.getColumns().contains(column))
                    return true;
            }
        }
        return false;
    }

    private void writes(Writer writer, List<List<String>> contentList) throws IOException {
        for (List<String> contents : contentList) {
            Collections.sort(contents);
            for (String script : contents) {
                writer.write(script);
                writer.write(";\n");
            }
        }
    }

    public static void main(String[] args) throws Exception {
        if (args.length < 3) {
            System.out.println("Usage: DdlGenerator org.hibernate.dialect.Oracle10gDialect /tmp zh_CN");
            return;
        }
        String dir = SystemInfo.getTmpDir();
        if (args.length > 1)
            dir = args[1];
        Locale locale = Locale.getDefault();
        if (args.length > 2)
            locale = Locales.toLocale(args[2]);
        String pattern = null;
        if (args.length > 3)
            pattern = args[3];
        new DdlGenerator((Dialect) ClreplacedLoaders.loadClreplaced(args[0]).newInstance(), locale).gen(dir, pattern);
    }
}

19 View Complete Implementation : AbstractGenericBasicType.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Override
public boolean[] toColumnNullness(Object value, Mapping mapping) {
    return value == null ? FALSE : TRUE;
}

19 View Complete Implementation : AttributeConverterGridTypeAdaptor.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Override
public int getColumnSpan(Mapping mapping) throws MappingException {
    return ormAdapter.getColumnSpan(mapping);
}

19 View Complete Implementation : BigDecimalPassThroughType.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Override
public int getColumnSpan(Mapping mapping) throws MappingException {
    return 1;
}

19 View Complete Implementation : GridTypeDelegatingToCoreType.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Override
public int getColumnSpan(Mapping mapping) throws MappingException {
    return delegate.getColumnSpan(mapping);
}

19 View Complete Implementation : GridTypeDelegatingToCoreType.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Override
public boolean[] toColumnNullness(Object value, Mapping mapping) {
    return delegate.toColumnNullness(value, mapping);
}

19 View Complete Implementation : UUIDType.java
Copyright GNU Lesser General Public License v2.1
Author : hibernate
@Override
public int getColumnSpan(Mapping mapping) {
    return 1;
}

19 View Complete Implementation : PostgreSQLIntervalFunction.java
Copyright Apache License 2.0
Author : igloo-project
@Override
public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
    return null;
}

19 View Complete Implementation : PostgreSQLRegexpOperatorFunction.java
Copyright Apache License 2.0
Author : igloo-project
@Override
public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
    return BooleanType.INSTANCE;
}

19 View Complete Implementation : ColumnMapperSingleColumnTypeAdapter.java
Copyright Apache License 2.0
Author : JadiraOrg
@Override
public boolean[] toColumnNullness(Object value, Mapping mapping) {
    return columnMapper.getHibernateType().toColumnNullness(value, mapping);
}

19 View Complete Implementation : ColumnMapperSingleColumnTypeAdapter.java
Copyright Apache License 2.0
Author : JadiraOrg
@Override
public int getColumnSpan(Mapping mapping) throws MappingException {
    return columnMapper.getHibernateType().getColumnSpan(mapping);
}

19 View Complete Implementation : ColumnMapperSingleColumnTypeAdapter.java
Copyright Apache License 2.0
Author : JadiraOrg
@Override
public Size[] dictatedSizes(Mapping mapping) throws MappingException {
    return columnMapper.getHibernateType().dictatedSizes(mapping);
}

19 View Complete Implementation : ColumnMapperSingleColumnTypeAdapter.java
Copyright Apache License 2.0
Author : JadiraOrg
@Override
public int[] sqlTypes(Mapping mapping) throws MappingException {
    return new int[] { columnMapper.getSqlType() };
}

19 View Complete Implementation : ColumnMapperSingleColumnTypeAdapter.java
Copyright Apache License 2.0
Author : JadiraOrg
@Override
public Size[] defaultSizes(Mapping mapping) throws MappingException {
    return columnMapper.getHibernateType().defaultSizes(mapping);
}

19 View Complete Implementation : PostgreSQLPlainToTSQueryFunction.java
Copyright GNU General Public License v3.0
Author : JuniperBot
@Override
public Type getReturnType(Type columnType, Mapping mapping) throws QueryException {
    return BooleanType.INSTANCE;
}

19 View Complete Implementation : PostgreSQLToRankCDFunction.java
Copyright GNU General Public License v3.0
Author : JuniperBot
@Override
public Type getReturnType(Type columnType, Mapping mapping) throws QueryException {
    return FloatType.INSTANCE;
}

19 View Complete Implementation : PostgreSQLFTSFunction.java
Copyright MIT License
Author : rieckpil
@Override
public Type getReturnType(Type columnType, Mapping mapping) throws QueryException {
    return new BooleanType();
}

19 View Complete Implementation : ImmutableType.java
Copyright Apache License 2.0
Author : vladmihalcea
@Override
public boolean[] toColumnNullness(Object value, Mapping mapping) {
    return value == null ? ArrayHelper.FALSE : ArrayHelper.TRUE;
}

19 View Complete Implementation : ImmutableType.java
Copyright Apache License 2.0
Author : vladmihalcea
@Override
public Size[] defaultSizes(Mapping mapping) throws MappingException {
    return dictatedSizes(mapping);
}

19 View Complete Implementation : ImmutableType.java
Copyright Apache License 2.0
Author : vladmihalcea
@Override
public int[] sqlTypes(Mapping mapping) throws MappingException {
    return sqlTypes();
}

19 View Complete Implementation : ImmutableType.java
Copyright Apache License 2.0
Author : vladmihalcea
@Override
public Size[] dictatedSizes(Mapping mapping) throws MappingException {
    return new Size[] { new Size() };
}

18 View Complete Implementation : ImmutableType.java
Copyright Apache License 2.0
Author : vladmihalcea
@Override
public Object fromXMLNode(Node xml, Mapping factory) throws HibernateException {
    Method valueOfMethod = ReflectionUtils.getMethodOrNull(clazz, "valueOf", String.clreplaced);
    return valueOfMethod != null ? ReflectionUtils.invokeStaticMethod(valueOfMethod, xml.getText()) : null;
}

8 View Complete Implementation : HibernateDbLoader.java
Copyright Apache License 2.0
Author : Jasig
/**
 * Generate create scripts and add them to the script list
 */
@SuppressWarnings("unchecked")
protected List<String> createScript(Collection<Table> tables, Dialect dialect, Mapping mapping, String defaultCatalog, String defaultSchema) {
    final List<String> script = new ArrayList<String>(tables.size() * 2);
    for (final Table table : tables) {
        if (table.isPhysicalTable()) {
            script.add(table.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
        }
    }
    for (final Table table : tables) {
        if (table.isPhysicalTable()) {
            for (final Iterator<UniqueKey> subIter = table.getUniqueKeyIterator(); subIter.hasNext(); ) {
                final UniqueKey uk = subIter.next();
                final String constraintString = uk.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema);
                if (StringUtils.isNotBlank(constraintString)) {
                    script.add(constraintString);
                }
            }
            for (final Iterator<Index> subIter = table.getIndexIterator(); subIter.hasNext(); ) {
                final Index index = subIter.next();
                script.add(index.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
            }
            if (dialect.hasAlterTable()) {
                for (final Iterator<ForeignKey> subIter = table.getForeignKeyIterator(); subIter.hasNext(); ) {
                    final ForeignKey fk = subIter.next();
                    if (fk.isPhysicalConstraint()) {
                        script.add(fk.sqlCreateString(dialect, mapping, defaultCatalog, defaultSchema));
                    }
                }
            }
        }
    }
    return script;
}

5 View Complete Implementation : SchemaValidator.java
Copyright GNU Lesser General Public License v3.0
Author : beangle
public String validateSchema(Configuration config, Dialect dialect, DatabaseMetadata databaseMetadata) {
    String defaultCatalog = sessionFactoryBean.getHibernateProperties().getProperty(Environment.DEFAULT_CATALOG);
    String defaultSchema = sessionFactoryBean.getHibernateProperties().getProperty(Environment.DEFAULT_SCHEMA);
    Mapping mapping = config.buildMapping();
    Iterator<?> iter = config.getTableMappings();
    while (iter.hasNext()) {
        Table table = (Table) iter.next();
        if (table.isPhysicalTable()) {
            TableMetadata tableInfo = databaseMetadata.getTableMetadata(table.getName(), (table.getSchema() == null) ? defaultSchema : table.getSchema(), (table.getCatalog() == null) ? defaultCatalog : table.getCatalog(), table.isQuoted());
            if (tableInfo == null) {
                reporter.append("Missing table: " + table.getName() + "\n");
            } else {
                validateColumns(table, dialect, mapping, tableInfo);
            }
        }
    }
    iter = iterateGenerators(config, dialect);
    while (iter.hasNext()) {
        PersistentIdentifierGenerator generator = (PersistentIdentifierGenerator) iter.next();
        Object key = generator.generatorKey();
        if (!databaseMetadata.isSequence(key) && !databaseMetadata.isTable(key)) {
            throw new HibernateException("Missing sequence or table: " + key);
        }
    }
    return null;
}

5 View Complete Implementation : SchemaValidator.java
Copyright GNU Lesser General Public License v3.0
Author : beangle
private void validateColumns(Table table, Dialect dialect, Mapping mapping, TableMetadata tableInfo) {
    Iterator<?> iter = table.getColumnIterator();
    Set<ColumnMetadata> processed = CollectUtils.newHashSet();
    String tableName = Table.qualify(tableInfo.getCatalog(), tableInfo.getSchema(), tableInfo.getName());
    while (iter.hasNext()) {
        Column col = (Column) iter.next();
        ColumnMetadata columnInfo = tableInfo.getColumnMetadata(col.getName());
        if (columnInfo == null) {
            reporter.append("Missing column: " + col.getName() + " in " + tableName);
        } else {
            final boolean typesMatch = col.getSqlType(dialect, mapping).toLowerCase().startsWith(columnInfo.getTypeName().toLowerCase()) || columnInfo.getTypeCode() == col.getSqlTypeCode(mapping);
            if (!typesMatch) {
                reporter.append("Wrong column type in " + tableName + " for column " + col.getName() + ". Found: " + columnInfo.getTypeName().toLowerCase() + ", expected: " + col.getSqlType(dialect, mapping));
            }
            processed.add(columnInfo);
        }
    }
    // 检查多出的列
    try {
        Field field = tableInfo.getClreplaced().getField("columns");
        @SuppressWarnings("unchecked")
        Set<ColumnMetadata> allColumns = CollectUtils.newHashSet(((Map<String, ColumnMetadata>) field.get(tableInfo)).values());
        allColumns.removeAll(processed);
        if (!allColumns.isEmpty()) {
            for (ColumnMetadata col : allColumns) {
                reporter.append("Extra column " + col.getName() + " in " + tableName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

5 View Complete Implementation : HibernateDbLoader.java
Copyright Apache License 2.0
Author : Jasig
@Override
public void process(DbLoaderConfig configuration) throws ParserConfigurationException, SAXException, IOException {
    final String scriptFile = configuration.getScriptFile();
    final List<String> script;
    if (scriptFile == null) {
        script = null;
    } else {
        script = new LinkedList<String>();
    }
    final ITableDataProvider tableData = this.loadTables(configuration, dialect);
    // Handle table drop/create
    if (configuration.isDropTables() || configuration.isCreateTables()) {
        // Load Table object model
        final Map<String, Table> tables = tableData.getTables();
        final Mapping mapping = this.configuration.buildMapping();
        final String defaultCatalog = this.configuration.getProperty(Environment.DEFAULT_CATALOG);
        final String defaultSchema = this.configuration.getProperty(Environment.DEFAULT_SCHEMA);
        final Map<String, DataAccessException> failedSql = new LinkedHashMap<String, DataAccessException>();
        // Generate and execute drop table scripts
        if (configuration.isDropTables()) {
            final List<String> dropScript = this.dropScript(tables.values(), dialect, defaultCatalog, defaultSchema);
            if (script == null) {
                this.logger.info("Dropping existing tables");
                for (final String sql : dropScript) {
                    this.logger.info(sql);
                    try {
                        jdbcOperations.update(sql);
                    } catch (NonTransientDataAccessResourceException dae) {
                        throw dae;
                    } catch (DataAccessException dae) {
                        failedSql.put(sql, dae);
                    }
                }
            } else {
                script.addAll(dropScript);
            }
        }
        // Log any drop/create statements that failed
        for (final Map.Entry<String, DataAccessException> failedSqlEntry : failedSql.entrySet()) {
            this.logger.warn("'" + failedSqlEntry.getKey() + "' failed to execute due to " + failedSqlEntry.getValue());
        }
        // Generate and execute create table scripts
        if (configuration.isCreateTables()) {
            final List<String> createScript = this.createScript(tables.values(), dialect, mapping, defaultCatalog, defaultSchema);
            if (script == null) {
                this.logger.info("Creating tables");
                for (final String sql : createScript) {
                    this.logger.info(sql);
                    jdbcOperations.update(sql);
                }
            } else {
                script.addAll(createScript);
            }
        }
    }
    // Perform database population
    if (script == null && configuration.isPopulateTables()) {
        this.logger.info("Populating database");
        final Map<String, Map<String, Integer>> tableColumnTypes = tableData.getTableColumnTypes();
        this.populateTables(configuration, tableColumnTypes);
    }
    // Write out the script file
    if (script != null) {
        for (final Lisreplacederator<String> iterator = script.lisreplacederator(); iterator.hasNext(); ) {
            final String sql = iterator.next();
            iterator.set(sql + ";");
        }
        final File outputFile = new File(scriptFile);
        FileUtils.writeLines(outputFile, script);
        this.logger.info("Saved DDL to: " + outputFile.getAbsolutePath());
    }
}