0

我有一个模型,每个类都扩展实体:

@MappedSuperclass
public abstract class Entity implements Serializable {
    private Long id;
    .
    .
    .
}

现在,在我的模型中,每个实体都可以有一个属性:

@javax.persistence.Entity
public class Attribute extends Entity {
    private Entity entity;
    private String name;
    private String value;
    .
    .
    .
}

我的问题是:如何映射类 Attribute 的实体属性?我的想法是将此属性存储为 entityClass 和 entityId,但我仍然不知道如何使用 JPA 来实现这一点?


扩展实体的具体类的示例:

@javax.persistence.Entity
public class Ball extends Entity {
    private Set<Attribute> attributes;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "entity")
    public Set<Attribute> getAttributes() {
        return attributes;
    }

    public void setAttributes(Set<Attribute> attributes) {
        this.attributes = attributes;
    }
}
4

2 回答 2

1

在 JPA 中没有简单的方法可以做到这一点。您可以将关系映射为 @Transient 并为 id 和类添加两个 @Basic 映射(可能使用属性 get/set 方法)。然后在模型代码中执行查询。

如果您使用的是 EclipseLink,您可以使用 @VariableOneToOne,

看,

http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_variableonetoone.htm#CHDDFDGF

于 2013-01-28T15:26:02.523 回答
0

根据您的评论,您需要在映射的超类中建立双向关系。不幸的是,您不能在 JPA 中这样做。原因是 aMappedSuperClass不是实体,其字段MappedSuperClass属于不同的子类。

来源JPA 2.0 规范(2.11.2)

(我不知道您到底想做什么,但是:)看来您正在尝试坚持持久性模型的元模型。如果您需要阅读它:您可以使用EntityManagerFactory.getMetamodel()

于 2013-01-27T08:49:49.397 回答