【发布时间】:2013-10-24 06:59:41
【问题描述】:
在我的项目中,我经常将 JPA/Hibernate 堆栈用于数据库。
定义persistence.xml 时,您有几个选项可以设置hibernate.hbm2ddl.auto。
如果设置为create,将在每次应用程序运行时重新创建表(当然,持久化数据会丢失)。也可以通过使用hibernate.hbm2ddl.import_files 设置db 夹具来导入初始数据。当设置为 update 时,只会创建新实体的表(将保留现有表中的持久数据)。
问题是这在开发时不太方便,我想要这样的行为:
- 在第一次应用程序运行时(当数据库中没有表时) - 就像
hibernate.hbm2ddl.auto设置为create(基于实体创建表)并导入预定义的数据库夹具 - 在所有后续运行中 - 就像将
hibernate.hbm2ddl.auto设置为update一样(为新实体创建新表,为旧实体保留表/数据)。
这样可以实现吗?
关于我的典型堆栈的更多信息:Spring Web 应用程序,在 Tomacat 上运行,数据库是 MySql,用于数据库访问的 JPA/Hibernate。
我的典型persistence.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<!-- value="create" to build a new database on each run; value="update" to modify an existing database; value="create-drop" means the same as "create" but also drops tables when Hibernate closes; value="validate" makes no changes to the database -->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
<property name="hibernate.hbm2ddl.import_files" value="/META-INF/spring/import.sql"/>
</properties>
</persistence-unit>
</persistence>
如果您需要有关我的应用程序配置/结构的其他信息,请发表评论。
【问题讨论】:
标签: spring hibernate jakarta-ee jpa persistence.xml