有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在JPA中重写annotationdefined表名?

我的应用程序中有一些表具有这种注释结构,我使用JpaRepository进行CRUD操作

@Entity
@Table(name = "FOO")
public class Foo implements Serializable {
  …
}

但是我只需要覆盖orm.xml或属性文件中的表名(而不是任何@Column等属性),而不更改实际代码。我已经搜索过了,但在Spring Data JPA中找不到这样做的方法。我是否遗漏了什么,或者它不受支持


共 (1) 个答案

  1. # 1 楼答案

    首先,Spring数据不是一个JPA提供者,只是一个“助手”库,提供了一个通用持久性操作的包装器。然而,JPA规范确实提供了一种通过XML映射文件覆盖注释的机制。因此,假设您的提供者(Hibernate、EclipseLink、OpenJPA或其他什么)完全实现了JPA规范,那么您应该能够做到这一点

    然而,似乎不能只覆盖表名:除非列名映射到默认值,那么,据我所见,您需要在映射文件中指定每一列——我想这有点不方便

    Pro JPA 2:掌握Java持久性API说明:

    The metadata-complete attribute is an attribute on the entity, mapped-superclass, and embeddable elements. If specified, all annotations on the specified class and on any fields or properties in the class will be ignored, and only the metadata in the mapping file will be considered as the set of metadata for the class. When metadata-complete is enabled, the same rules that we applied to annotated entities will still apply when using XML-mapped entities. For example, the identifier must be mapped, and all relationships must be specified with their corresponding cardinality mappings inside the entity element.

    所以你需要在orm中输入一个条目。xml,如下图所示,根据需要添加其他属性

     <entity-mappings>
        <entity class="examples.Foo" metadata-complete="true">
            <table name="NEW_FOO"/>
            <attributes>
                <id name="id"/>
            </attributes>
        </entity>
    </entity-mappings>