您可以直接使用SchemaExport类生成DDL脚本:
对于Hibernate 4:
Configuration config = new Configuration(); Properties properties = new Properties(); properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); properties.put("hibernate.connection.url", "jdbc:postgresql://localhost:5432/Test"); properties.put("hibernate.connection.username", "username"); properties.put("hibernate.connection.password", "password"); properties.put("hibernate.connection.driver_class", "org.postgresql.Driver"); properties.put("hibernate.show_sql", "true"); config.setProperties(properties); config.addAnnotatedClass(MyMappedPojo1.class); config.addAnnotatedClass(MyMappedPojo2.class); .................. SchemaExport schemaExport = new SchemaExport(config); schemaExport.setDelimiter(";"); schemaExport.create(true, false);Hibernate 5的更新:
Properties properties = new Properties(); properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect"); properties.put("hibernate.connection.url", "jdbc:postgresql://localhost:5432/Test"); properties.put("hibernate.connection.username", "username"); properties.put("hibernate.connection.password", "password"); properties.put("hibernate.connection.driver_class", "org.postgresql.Driver"); properties.put("hibernate.show_sql", "true"); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(properties).build(); metadataSources metadataSource = new metadataSources(serviceRegistry); metadataSource.addAnnotatedClass(MyMappedPojo1.class); metadataSource.addAnnotatedClass(MyMappedPojo2.class); ........... metadata meta = metadataSource.buildmetadata(); SchemaExport schemaExport = new SchemaExport(); schemaExport.setDelimiter(";"); schemaExport.execute(EnumSet.of(TargetType.STDOUT), Action.CREATE, meta);


