在本教程中,我们将了解什么是hibernate 中的hbm2ddl.auto配置。
Hibernate hbm2ddl.auto:
hbm2ddl.auto 是一个休眠配置属性。它用于在创建 SessionFactory 时验证模式 DDL 并将其导出到数据库。
如果我们想使用它,我们应该将适当的值传递给hibernate.cfg。xml 如下所示。
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">value</property>
</session-factory>
</hibernate-configuration>
通过定义 hbm2ddl.auto 属性,我们可以从 hibernate 框架执行 DDL(数据定义语言)命令,同时创建 SessionFactory 本身。
Hibernate的hbm2ddl.auto属性创建或验证数据库表。
hbm2ddl.auto 的可能值:
- create
- validate
- update
- create-drop
句法 :
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">validate/create/update/create-drop</property>
Or
<property name="hbm2ddl.auto" value="validate/create/update/create-drop" />
</session-factory>
</hibernate-configuration>
hbm2ddl.auto create:
如果值为create,则Hibernate首先删除现有表的数据和结构,然后创建新表并在新创建的表上执行操作。
<property name="hbm2ddl.auto">create</property>
值“ create ”的唯一问题是,我们丢失了现有的表数据。
hbm2ddl.auto validate :
如果该值是validate 则 hibernate 只验证表结构——表和列是否存在。如果该表不存在,则Hibernate 将引发异常。
验证是 hbm2ddl.auto 的默认值。
<property name="hbm2ddl.auto">validate</property>
hbm2ddl.auto update :
如果值是update ,那么 Hibernate 会检查表和列。如果表不存在,则它会创建新表,并且如果列不存在,它会为其创建新列。
<property name="hbm2ddl.auto">update</property>
但是在值“更新”的情况下,hibernate 不会删除任何现有的表,因此我们不会丢失现有的表数据,可以用于生产环境。
hbm2ddl.auto create-drop:
如果该值为create-drop那么 Hibernate 首先检查表并执行必要的操作,最后在所有操作完成后删除表。
<property name="hbm2ddl.auto">create-drop</property>
值“ create-drop ”用于对Hibernate 代码进行单元测试。