[英]JPA @OneToMany and @ManyToOne: back reference is null
I have the following data structure. 我有以下数据结构。
@Entity
public class Device extends AbstractEntity implements Serializable{
private int id;
//...
private List<Item> items;
@OneToMany(fetch=FetchType.EAGER)
public List<Item> getItems() {
return configurationItems;
}
}
each item contains back reference to Device: 每个项目都包含对设备的反向引用:
class Item {
private Device;
@ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH} )
public Device getDevice() {
return device;
}
}
I can create Device, add items and save all this. 我可以创建设备,添加项目并保存所有这些。 The I can retrieve the objects from DB and everything is working except the reference to device that item holds.
我可以从数据库中检索对象,除了对项目所持有的设备的引用外,一切正常。
And it does not matter how do I read the items: 1. read device with all associated items 2. read items 如何读取项目并不重要:1。读取所有相关项目的设备2.读取项目
The Device reference is always null. Device引用始终为null。 I guess that something is wrong with my annotation @ManyToOne.
我想我的注释@ManyToOne出了点问题。
I am using hibernate and spring, implementing DAO by subclassing HibernateDaoSupport. 我正在使用hibernate和spring,通过继承HibernateDaoSupport实现DAO。
Here is the code example that retrieves all items: 以下是检索所有项目的代码示例:
getHibernateTemplate().loadAll(Item.class)
Since you have a bidirectional one-to-many relathionship, you need to use mappedBy
: 由于您具有双向一对多关系,因此需要使用
mappedBy
:
@OneToMany(fetch=FetchType.EAGER, mappedBy = "device")
public List<Item> getItems() {
return configurationItems;
}
See also: 也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.