Honenate OnetoMany,ManyToOne映射为null [英] Hibernate OnetoMany,ManyToOne Mapping Giving null

查看:114
本文介绍了Honenate OnetoMany,ManyToOne映射为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个名为PurchaseList.java和PurchaseListItems.java的类

I have 2 classes called PurchaseList.java and PurchaseListItems.java

我必须在PurchaseListItems中映射PurchaseList

I have to map PurchaseList in PurchaseListItems

PurchaseList.java

PurchaseList.java

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name="pl_id",referencedColumnName="id")
private List<PurchaseListItems> purchaseListItems;

PurchaseListItems.java

PurchaseListItems.java

@ManyToOne
@JoinColumn(name="pl_id")
private PurchaseList purchaseListId;

一切都很好,但是我在pl_id中得到的是空值.请告诉我我错了

Everything is fine but i am getting null in pl_id. Please tell where i am wrong

推荐答案

您的映射实际上定义了两个独立的单向关系.您想要的是一个双向关系.下面的代码将建立双向关系

Your mapping actually defines two independent unidirectional relations. What you want is one bidirectional relation.The following code will establish the bidirectional relation

@OneToMany(cascade = CascadeType.ALL, mappedBy = "purchaseListId")
@JoinColumn(name="pl_id",referencedColumnName="id")
private List<PurchaseListItems> purchaseListItems;

mappedBy属性是必需的,因为提供者无法自动确定指定的关系实际上形成了单个关系.可以使用实例成员的Java类型,但是如果您有多个相同类型的成员,该怎么办.在许多情况下,您有两个单一关系.示例:

The mappedBy attribute is necessary since there is no way for the provider to automatically determine that the specified relations actually form a single relation. One could use the Java type of the instance member but then what if you have multiple members of the same type. And there are many scenarios where you have two single relations. Example:

OneToMany:用户-> ForumThread(用户创建的线程)

OneToMany: User -> ForumThread (the threads created by the user)

ManyToOne:ForumThread->用户(关闭线程的用户.显然不一定是启动线程的用户)

ManyToOne: ForumThread -> User (the user who closed the thread. obviously not necessarily the one who started the thread)

这是两个独立的关系,必须这样对待.如果您的持久性仅仅由于类型和多样性匹配而建立了双向关系,您会感到非常惊讶.

These are two independent relations and must be treated as such. You would be quite surprised if your persistence provide just made a bidirectional relation out of that just because the types and multiplicity matched.

还请注意,任何JPA提供程序都不会自动管理双向关系,这意味着相反的一面不会在对象模型中自动更新/设置,因此不会在db中自动更新/设置.你必须自己做.顺便说一下,在我的所有项目中,双向关系都是一个麻烦,我建议避免使用它们.

Also note that bidirectional relations are not automatically managed by any JPA provider, meaning that the inverse side is not automatically updated/set in your object model and thus not in the db. You have to do that yourself. By the way, in all my projects bidirectional relationships were a pain in the ass and I think it is advisable to avoid them.

这篇关于Honenate OnetoMany,ManyToOne映射为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆