java - 有什么方法可以从实体获取字段而不实际加入该表?

标签 java jpa

我不确定这是否可能,但仅了解 JPA 的基础知识,我想问这是否可能。基本上我有一个实体(我们将其称为 MyEntity),上面有一堆字段。我们现在想要第二个实体,它具有与 MyEntity 相同的所有字段以及一些它自己的字段。其用例是归档这些实体。我们希望将所有存档实体存储在与 MyEntity 不同的表中,这样我们就不必使用 archived=false 限定所有查询。 MyEntity 的 JPA 注释如下所示:

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE")
public abstract class MyEntity
{
    ....

有多个类扩展了这个抽象类,每个类都带有 @DiscriminatorValue 注释

对于我的存档实体 (MyArchivedEntity),我想要类似的内容:

@Entity
public class MyArchivedEntity
{
    private MyEntity entity;
    private String archiveSpecificField;
    ....

这样做的问题当然是它需要加入 MyEntity 表并获取特定的 MyEntity 记录来填充 entity > 领域。是否有某种注释或我可以做的事情来将相同的字段/列从该实体(MyEntity)获取到该实体(MyArchivedEntity)?

就像我一开始所说的,我不确定这是否可能,但我希望我已经很好地解释了我想要实现的最终目标,以便有某种方法可以实现它。如果有什么区别的话,我将 PostgreSQL 与 EclipseLink 结合使用。

最佳答案

您可以使用@MappedSuperclass AbstractParentEntity 成为两者的父类(super class) MyEntityMyArchiveEntity 。所以你会得到类似下面的内容:

@MappedSuperclass
public abstract class AbstractParentEntity {
    public String someField;
    ...
}

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE")
public abstract class MyEntity extends AbstractParentEntity 
{
   //here you don't have any field (they all move to  AbstractParentEntity
   // (or, at least all the fields that need to be archivied are now declared in parent class)
   ....
}

@Entity
public class MyArchivedEntity extends AbstractParentEntity  
{
    private String archiveSpecificField;
    ....

有关 MappedSuperclass 的更多信息 here :

Mapped superclass inheritance allows inheritance to be used in the object model, when it does not exist in the data model. It is similar to table per class inheritance, but does not allow querying, persisting, or relationships to the superclass. Its' main purpose is to allow mappings information to be inherited by its' subclasses. The subclasses are responsible for defining the table, id and other information, and can modify any of the inherited mappings. A common usage of a mapped superclass is to define a common PersistentObject for your application to define common behavoir and mappings such as the id and version. A mapped superclass normally should be an abstract class. A mapped superclass is not an Entity but is instead defined though the @MappedSuperclass annotation or the <mapped-superclass> element.

关于java - 有什么方法可以从实体获取字段而不实际加入该表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15105355/

相关文章:

java - Spring MVC 处理表单填充和提交

java - 如何正确处理默认变量值不正确

database - JPA + Spring 如何用自定义表和数据初始化数据库

hibernate - 如何在 play 框架中运行 JPA 查询

java - 在 NanoHTTPD 中检索 HTTP 正文

java - 在 Cordova-Android 上扫描网络打印机

java - JsonTest 导致 Spring 自动配置失败

java - @OneToMany 通过mappedBy 而不使用@JoinColumns

java - JPA持久性问题

java - 使用片段的 Spring Data Jpa 存储库如何应用查询提示和实体图