【问题标题】:How can I load a .sql file when running a Maven/Hibernate project?运行 Maven/Hibernate 项目时如何加载 .sql 文件?
【发布时间】:2012-09-27 19:21:13
【问题描述】:

我正在使用 hbm2ddl 创建我的表,它工作得很好,但我也希望 hibernate 每次运行我的项目时加载一个 .sql 文件来填充数据库。 我发现如果我的 .sql 文件在类路径中,Hibernate 应该这样做,但它似乎不起作用。

我不确定文件是否在类路径中,我不知道如何找到它。 目前我的 load.sql 在 Other Sources/csr/main/resources/

我用谷歌搜索并读到我可以在我的项目的属性/库菜单中添加一个文件到类路径,但似乎 Maven 项目没有该部分。

我将 Mysql 与 JDBC 和 Netbeans 7.1.2 一起使用。

【问题讨论】:

  • 我没有答案,但我很好奇为什么每次运行应用程序时都要重建数据库。
  • 在这种情况下听起来更像是测试,但我不确定......
  • @foampile 示例:我们有一个执行此操作的开发配置(因为开发人员倾向于破坏数据嘿嘿)。当然live系统的配置不​​会重建数据库。

标签: sql hibernate maven


【解决方案1】:

您必须在 hibernate.xml 中指定要加载的 SQL 文件

<hibernate-configuration>
    <session-factory>
        ... some other stuff comes here     
        <property name="hibernate.hbm2ddl.auto">create-drop</property>
        <property name="hibernate.hbm2ddl.import_files">
            /import1.sql, /import2.sql
        </property>
    </session-factory>
<hibernate-configuration>

仅当 hbm2ddl.auto = create-drop 时才会加载脚本。导入文件在所有其他选项上都被忽略 请注意,此文件中只允许使用单行语句。

Hibernate Configuration, Chapter 3.4 中描述了这两个属性

【讨论】:

  • 如果hbm2ddl.auto=create,也会加载脚本
【解决方案2】:

您可以使用sql-maven-plugin 来执行此类操作。这可以运行sql脚本等。hbm2ddl创建可以由sql-maven-plugin执行的SQL脚本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2020-03-01
    • 2018-08-07
    • 2016-07-20
    • 2016-04-15
    • 1970-01-01
    • 2013-04-20
    相关资源
    最近更新 更多