Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 331
AlexR Avatar asked Nov 18 '10 18:11

AlexR


1 Answers

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
like image 67
axtavt Avatar answered Sep 29 '22 01:09

axtavt