gpt4 book ai didi

java - JPA实体字段引用OneToOne递归

转载 作者:行者123 更新时间:2023-12-02 04:29:12 25 4
gpt4 key购买 nike

当我persist()我的实体时,我收到此错误。我认为错误的原因是关系,我的想法是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

这是我的主要实体:

@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 **/

}

有人帮我解决这个问题吗?谢谢!

最佳答案

您应该检查 mappedBy 的含义:它不引用包含 ID 的字段(JPA 足够聪明,可以自己找到该字段),但它引用另一个 XToOne “拥有”映射的字段

public abstract String mappedBy

(Optional) The field that owns the relationship. This element is only specified on the inverse (non-owning) side of the association.

(来自OneToOne的javadoc)

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

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

关于java - JPA实体字段引用OneToOne递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31711922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com