JPA实体字段引用OneToOne递归

时间:2015-07-29 21:58:11

标签: java spring hibernate jpa

当我坚持()我的实体时,我收到此错误。我认为错误的原因是关系,我的想法是FolderEntity(代表一个虚拟文件夹)可以留在另一个(只有一个)然后我创建了对self的引用(在扩展类中,因为所有资源都可以在文件夹内,文件夹是资源)

org.hibernate.AnnotationException: Referenced property not a (One|Many)ToOne: com.editor.entity.FolderEntity.id in mappedBy of com.editor.entity.FolderEntity.folderId

这是我的主要Entity

@MappedSuperclass
public abstract class Entity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ID", nullable = false)
    private Integer id;

    /** getter/setter **/

}

然后我在我的ResourceEntity实体中扩展它:

@MappedSuperclass
public class ResourceEntity extends Entity {

    @Column(name = "NAME", length = Lengths.NAME40, unique = true, nullable = false)
    private String name;

    @Column(name = "DESCRIPTION", length = Lengths.DESCRIPTION1000, unique = false, nullable = true)
    private String description;

    @JoinColumn(name = "FOLDER_ID", updatable = true, nullable = false)
    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "id")
    private FolderEntity folderId;

    /** getter/setter **/

}

最后,我正在与这个实体合作:

@javax.persistence.Entity
@Table(name = "EDITOR_FOLDERS")
@NamedQueries({
        @NamedQuery(name = FolderEntity.ALL_FOLDERS, query = "select f from FolderEntity f"),
        @NamedQuery(name = FolderEntity.FOLDER_BY_NAME, query = "select f from FolderEntity f where name = :name and resourceType = :resourceType") })
public class FolderEntity extends ResourceEntity {


    public static final String ALL_FOLDERS = "findAllFolders";
    public static final String FOLDER_BY_NAME = "findAllFoldersByName";

    @Column(name = "RESOURCE_TYPE", length = Lengths.CODE, unique = false, nullable = false)
    private Integer resourceType;
    /** getter/setter **/

}

Anybodys帮我解决了这个问题?谢谢!

1 个答案:

答案 0 :(得分:2)

你应该检查mappedBy的含义:它没有引用包含ID的字段(JPA足够聪明,可以自己找到它),但它引用了另一个 XToOne "拥有的领域"映射

  

public abstract String mappedBy

     

(可选)拥有该关系的字段。此元素仅在关联的反向(非拥有)侧指定。

(来自OneToOne的javadoc)

在您的情况下,您不需要mappedBy,因为您在拥有方面。您应该将属性命名为folder,因为您引用的不是ID,而是实体。

另一个评论:如果您打算将应用程序中的可能值定义为常量,请使用enum resourceType