gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:37:38 24 4
gpt4 key购买 nike

我们目前正在使用Hibernate 3,并且使用Hibernate Tools来为数据库模式生成SQL脚本。

我们使用以下Ant任务

<hibernatetool destdir="${target}">
<jpaconfiguration persistenceunit="@{persistenceUnit}" propertyfile="@{propertyfile}"/>
<classpath refid="@{classpathid}"/>
<!-- the file name is relative to $destdir -->
<hbm2ddl outputfilename="@{output}" format="true" export="false" drop="false"/>
</hibernatetool>

我们想切换到Hibernate 4:如果没有Hibernate工具,如何实现类似的目标?

最佳答案

您可以直接使用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(";");

/**Just dump the schema SQLs to the console , but not execute them ***/
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);

关于hibernate - 使用Hibernate 4生成SQL DB创建脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14014247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com