利用hibernate生成建表语句

不使用jpa的注解,还是想利用hibernate已经做好的适配去生成建表的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>

实例

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

相关推荐