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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With