在基于 OpenJPA 的 jpa-2.0 功能部件中,可生成数据定义语言 (DDL),或直接与数据库交互以使用 SchemaMapper 工具根据 JPA 实体定义来定义表模式。在基于 EclipseLink 的 jpa-2.1
功能部件中,可使用添加至 JPA 2.1 规范的新模式生成器功能部件,此功能部件的功能类似 OpenJPA SchemaMapper。
关于此任务
如果需要类似 OpenJPA SchemaMapper 的功能,那么可配置 JPA 2.1 规范中的模式生成器功能部件。
过程
- 在 persistence.xml 文件的持久性单元定义中,指定数据库操作属性及可能值(none、create、drop 和 drop-and-create)。 每个值对应针对数据库执行的操作。以下示例会使系统删除对应持久性单元中指定的实体的表并在原地创建新表。
<persistence-unit name="pu">
<properties>
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create" />
...
</properties>
</persistence-unit>
- 指定脚本操作属性及可能值(none、create、drop 和 drop-and-create)。 如果指定 none 以外的任何值,那么还必须指定目标属性。这意味着,如果脚本操作为 create(此操作为实体定义生成创建语句),那么必须指定对应创建目标属性及这些语句写至的目标文件。
<persistence-unit name="pu">
<properties>
<property name="javax.persistence.schema-generation.scripts.action"
value="drop-and-create" />
<property name="javax.persistence.schema-generation.scripts.create-target"
value="createTargetFile.ddl"/>
<property name="javax.persistence.schema-generation.scripts.drop-target"
value="sampleDrop.ddl"/>
...
</properties>
</persistence-unit>