gpt4 book ai didi

java - JPA 自引用关系定义不正确

转载 作者:搜寻专家 更新时间:2023-11-01 02:09:40 24 4
gpt4 key购买 nike

我需要一些关于 JPA 自引用关系的帮助。我认为有些东西我没有正确定义。

我有一个名为 ItemEntity 的 JPA 实体 bean。有两种类型的项目。父项和子项。父项可以有多个子项,子项只有一个父项。所以这实际上是一个 ManyToOne/OneToMany JPA 自引用关系。

在我的数据库中,项目表看起来像这样......

item_no,parent_item_no,item_description
111,null,This is my parent item
222,111,This is my child item

所以在我的 java 程序中,当我在项目 111 上调用 itemEntity.getChildren 时,我希望看到 222,但是我得到的是 null。

这是我定义我的 JPA 关系的方式...

@Entity(name = "stg_item")
public class ItemEntity implements java.io.Serializable {

@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "itemid")
@TableGenerator(name = "itemid", table = "stg_items_sequence", allocationSize = 1)
private Long id;

@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "item_no", referencedColumnName = "parent_item_no")
private ItemEntity parent;

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "parent")
private Collection<ItemEntity> children;

谁能告诉我我做错了什么?

项目实体与我的另一个名为 stg_import_payload 的实体具有 @ManyToOne 关系。这是我正在使用的命名查询。也许我必须对命名查询做一些特殊的事情?

    "SELECT x "
+ " FROM stg_import_payload x "
+ " WHERE x.processedInd='N' "
+ " AND EXISTS (SELECT stg_item FROM stg_item stg_item WHERE stg_item.importPayload = x AND stg_item.processedInd='N') ";

谢谢。

最佳答案

文档:

String javax.persistence.JoinColumn.referencedColumnName()

(Optional) The name of the column referenced by this foreign key column.

When used with entity relationship mappings other than the cases described here, the referenced column is in the table of the target entity.When used with a unidirectional OneToMany foreign key mapping, the referenced column is in the table of the source entity.When used inside a JoinTable annotation, the referenced key column is in the entity table of the owning entity, or inverse entity if the join is part of the inverse join definition.When used in a CollectionTable mapping, the referenced column is in the table of the entity containing the collection.Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.

你应该改变这个:

@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "item_no", referencedColumnName = "parent_item_no")
private ItemEntity parent;

@ManyToOne(fetch = FetchType.LAZY, optional = true)
private ItemEntity parent;

对我有用

关于java - JPA 自引用关系定义不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20559098/

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