Java 如何使用JPA2.0在DB中将属性映射为类和Id

Java 如何使用JPA2.0在DB中将属性映射为类和Id,java,jpa,jpa-2.0,Java,Jpa,Jpa 2.0,我有一个模型,每个类扩展实体: @MappedSuperclass public abstract class Entity implements Serializable { private Long id; . . . } @javax.persistence.Entity public class Ball extends Entity { private Set<Attribute> attributes; @OneToMa

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

@MappedSuperclass
public abstract class Entity implements Serializable {
    private Long id;
    .
    .
    .
}
@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;
    }
}
现在,在我的模型中,每个实体都可以有一个属性:

@javax.persistence.Entity
public class Attribute extends Entity {
    private Entity entity;
    private String name;
    private String value;
    .
    .
    .
}
我的问题是:如何映射类属性的实体属性?我的想法是将此属性存储为entityClass和entityId,但我仍然不知道如何使用JPA实现这一点


扩展实体的具体类示例:

@MappedSuperclass
public abstract class Entity implements Serializable {
    private Long id;
    .
    .
    .
}
@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;
    }
}
@javax.persistence.Entity
公共类Ball扩展实体{
私有集属性;
@OneToMany(cascade=CascadeType.ALL,mappedBy=“entity”)
公共集getAttributes(){
返回属性;
}
公共void集合属性(集合属性){
this.attributes=属性;
}
}

根据您的注释,您需要在映射的超类中建立双向关系。不幸的是,在JPA中你无法做到这一点。原因是
MappedSuperClass
不是实体,
MappedSuperClass
的字段属于不同的子类

资料来源(2.11.2)

(我不知道你到底想干什么,但是:)
似乎您正在尝试持久化持久化模型的元模型。如果你需要阅读:你可以使用JPA中没有简单的方法。您可以将关系映射为@Transient,并为id和类添加两个@Basic映射(可能使用属性get/set方法)。然后在模型代码中执行查询

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

看,


你的意思是它与其他实体有1-1关系不,有1-*关系。例如:我有实体球->球扩展实体和球有一个属性集属性。所以我需要属性和实体(球)之间的双向关系,这听起来像是一件可怕的事情。你的最终目标是什么?您希望如何将其存储在数据库中?在我写问题时,我希望将其存储在一个名为“Attribute”的表中,其中实体将存储为具体的类名和id?为什么可怕?不完全是在映射超类中。我只是在我的问题中添加了一个例子,如何实现一些扩展我的实体的具体类。我读了一点,发现@Transformation注释在这里可能很有用。谢谢你的回答。