JPA自引用关系定义不正确

Ric*_*hie 4 java jpa

我需要一些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
Run Code Online (Sandbox Code Playgroud)

所以在我的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;
Run Code Online (Sandbox Code Playgroud)

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

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

    "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') ";
Run Code Online (Sandbox Code Playgroud)

谢谢.

Hen*_*ker 6

文档:

字符串javax.persistence.JoinColumn.referencedColumnName()

(可选)此外键列引用的列的名称.

当与此处描述的情况之外的实体关系映射一起使用时,引用的列位于目标实体的表中.当与单向OneToMany外键映射一起使用时,引用的列位于源实体的表中.当在JoinTable注释中使用时,引用的键列位于拥有实体的实体表中,如果连接是反向连接定义的一部分.在CollectionTable映射中使用时,引用的列位于包含该集合的实体的表中.默认值(仅在使用单个连接列时适用):与引用表的主键列相同的名称.

你应该改变这个:

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

@ManyToOne(fetch = FetchType.LAZY, optional = true)
private ItemEntity parent;
Run Code Online (Sandbox Code Playgroud)

这个对我有用