我真的想知道更多关于更新,导出和值,可以给hibernate.hbm2ddl.auto 我需要知道什么时候使用更新,什么时候不?另一种选择是什么?

以下是在DB中可能发生的变化:

新表 旧表中的新列 列删除 事件解释列的数据类型发生变化 列的类型更改了其属性 表了 事件解释列值发生变化

在每种情况下,最佳解决方案是什么?


当前回答

来自社区文档:

hibernate.hbm2ddl。auto在创建SessionFactory时自动验证或将模式DDL导出到数据库。使用create-drop,当SessionFactory显式关闭时,数据库模式将被删除。 例如:validate | update | create | create-drop

所以可能的选项是,

Validate:验证模式,不对数据库进行任何更改。 Create-only:创建数据库。 Drop:生成数据库删除。 Update:更新模式。 Create:创建模式,销毁之前的数据。 create-drop:当SessionFactory显式关闭时删除模式,通常是在应用程序停止时。 None:不对模式进行任何操作,不对数据库进行任何更改

这些选项似乎是开发人员的工具,而不是为了方便任何生产级别的数据库,你可能想看看下面的问题;Hibernate: hbm2ddl。自动=更新生产?

其他回答

我会使用liquibase来更新您的数据库。Hibernate的模式更新特性实际上只适用于开发新特性的开发人员。在生产环境中,需要更谨慎地处理db升级。

首先,hbm2ddl配置属性的可能值如下:

none - No action is performed. The schema will not be generated. create-only - The database schema will be generated. drop - The database schema will be dropped. create - The database schema will be dropped and created afterward. create-drop - The database schema will be dropped and created afterward. Upon closing the SessionFactory, the database schema will be dropped. validate - The database schema will be validated using the entity mappings. update - The database schema will be updated by comparing the existing database schema with the entity mappings.

hibernate.hbm2ddl。Auto ="update"很方便,但如果您计划添加函数或执行一些自定义脚本,则不太灵活。

所以,最灵活的方法是使用Flyway。

但是,即使使用Flyway,仍然可以使用hbm2ddl生成初始迁移脚本。

来自社区文档:

hibernate.hbm2ddl。auto在创建SessionFactory时自动验证或将模式DDL导出到数据库。使用create-drop,当SessionFactory显式关闭时,数据库模式将被删除。 例如:validate | update | create | create-drop

所以可能的选项是,

Validate:验证模式,不对数据库进行任何更改。 Create-only:创建数据库。 Drop:生成数据库删除。 Update:更新模式。 Create:创建模式,销毁之前的数据。 create-drop:当SessionFactory显式关闭时删除模式,通常是在应用程序停止时。 None:不对模式进行任何操作,不对数据库进行任何更改

这些选项似乎是开发人员的工具,而不是为了方便任何生产级别的数据库,你可能想看看下面的问题;Hibernate: hbm2ddl。自动=更新生产?

validate: It validates the schema and makes no changes to the DB. Assume you have added a new column in the mapping file and perform the insert operation, it will throw an Exception "missing the XYZ column" because the existing schema is different than the object you are going to insert. If you alter the table by adding that new column manually then perform the Insert operation then it will definitely insert all columns along with the new column to the Table. Means it doesn't make any changes/alters the existing schema/table.

更新:在执行操作时,会改变数据库中已有的表。 您可以使用hbm2ddl的这个选项添加或删除列。 但是如果你要添加一个'NOT NULL'的新列,那么它将忽略向DB添加特定的列。因为如果你想在现有的表中添加“NOT NULL”列,表必须是空的。

综上所述…… 注意,这个属性叫做dll。auto和应该只控制dll操作(创建/删除模式/表),我惊讶地发现它也与dml有关:只有更新将允许插入数据,这是dml操作。

在试图将数据填充到内存数据库时被此捕获;只有更新有效。