Using hibernate to Generate Table Building Statements

  hibernate

Order

Do not use jpa’s comments, or want to use hibernate’s adaptation to generate table-building sql.

maven

    <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.11.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.11.Final</version>
        </dependency>

Example

            Oracle10gDialect dialect = new Oracle10gDialect();
            DatabaseMetadata databaseMetadata = new DatabaseMetadata(dataSource.getConnection(),dialect, null);
            TableMetadata tableMetadata = databaseMetadata.getTableMetadata("demotable", "demoschema", "", false);
            Field field = FieldUtils.getField(TableMetadata.class,"columns",true);
            Map<String,ColumnMetadata> columns = (Map<String, ColumnMetadata>) field.get(tableMetadata);

            Table table = new Table("demotable");
            columns.values().stream().forEach(e -> {
                Column column = new Column(e.getName());
                column.setNullable("YES".equals(e.getNullable()));
                column.setSqlType(e.getTypeName());
                table.addColumn(column);
            });
            System.out.println("table.sqlCreateString(dialect,null,null,"demoschema"));