且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Hibernate 4 生成 SQL DB 创建脚本

更新时间:2023-01-23 10:54:58

可以直接使用SchemaExport 类来生成 DDL 脚本:

You can directly use the SchemaExport class to generate the DDL script :

对于休眠 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(";");

    /**Just dump the schema SQLs to the console , but not execute them ***/
    schemaExport.create(true, false);

Hibernate 5 更新:


Update for 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);