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 {
priv开发者_运维问答ate 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
The Device reference is always null. I guess that something is wrong with my annotation @ManyToOne.
I am using hibernate and spring, implementing DAO by subclassing HibernateDaoSupport.
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
:
@OneToMany(fetch=FetchType.EAGER, mappedBy = "device")
public List<Item> getItems() {
return configurationItems;
}
See also:
- Hibernate Annotations Reference, 2.2.5.3.1.1. Bidirectional
精彩评论