【问题标题】:How create the database through Hibernate如何通过 Hibernate 创建数据库
【发布时间】:2014-06-23 03:25:57
【问题描述】:

在我的 spring 项目中,我使用 Hibernate 将我的实体类导出到以前创建的数据库。但这需要最终用户知道如何在数据库管理系统中创建数据库(目前我使用的是 Postgresql)。

有没有什么办法,只给安装postgresql的机器(以及第一次运行应用程序时提供的用户名和密码),如果没有,Hibernate会在服务器中创建一个新数据库不存在?

【问题讨论】:

标签: java spring hibernate postgresql


【解决方案1】:

查看hibernate.hbm2ddl.auto 的参数hibernate.cfg.xml 文件。我建议你这个链接:Hibernate hbm2ddl.auto, possible values and what they do - any official explanation?

【讨论】:

  • 我已经在数据库中创建/更新了表,我现在希望能够通过 Hibernate 在服务器中创建 DATABASE,以避免将此任务交给用户。
【解决方案2】:

如果你的配置是这样的

<hibernate-configuration>

  <session-factory>

    <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="connection.driver_class">org.postgresql.Driver</property>
    <property name="connection.url">jdbc:postgresql://host:port/database</property>
    <property name="connection.username">username</property>
    <property name="connection.password">password</property>


    <property name="current_session_context_class">thread</property>
    <property name="hibernate.show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
  </session-factory>
</hibernate-configuration>

然后Hibernate会自动创建数据库。

更新:

好的,现在我明白你想要什么了。你想用 Hibernate 启动 Postgresql 服务器。这不可能。 Hibernate 不这样做。

你可以这样做

  1. 另一个以您的应用程序开头的脚本
  2. maven/ant 目标。
  3. 构建作业

但最好的解决方案是使用不需要外部服务器的内存数据库(例如 H2 或 Java derby)

另请参阅 Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Postgres database create if not exists

【讨论】:

【解决方案3】:

运行“CREATE DATABASE ...”(请参阅​​http://www.postgresql.org/docs/9.0/static/sql-createdatabase.html)作为本机 SQL 查询 ...

.createSQLQuery(" ... ").executeUpdate(); ...

Hibernate 将 - 至少据我所知 - 不会创建数据库,只会创建其中的表。

我想您需要通过第二个持久性单元/连接来连接到 postgresql,因为这种方法具有先有鸡还是先有蛋的性质。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2013-12-24
    • 2011-01-27
    • 2010-10-24
    • 2013-03-02
    • 2014-01-30
    • 1970-01-01
    相关资源
    最近更新 更多