Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate OnetoMany,ManyToOne Mapping Giving null

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

I have to map PurchaseList in PurchaseListItems

PurchaseList.java

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

PurchaseListItems.java

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

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

like image 246
sainath reddy Avatar asked Mar 08 '13 05:03

sainath reddy


1 Answers

  1. The @JoinColumn annotation belongs on the @ManyToOne side of the relationship - but not on the @OneToMany side - remove it from the @OneToMany side.

  2. Cascade is used to cascade DELETE/READ/UPDATE operations..., but it does not automatically populate the ID column on the "child" side of a foreign key. In fact, it doesn't populate the java references to objects on either side of the FK relationship. You need to manually setup relationship data on both sides of bidirectional relationships:

    myPurchaseListItem.setPurchaseList(myPurchaseList);
    myPurchaseList.setPurchaseListItem(myPurchaseListItem);

    From the JPA 2 spec:

    Bidirectional relationships between managed entities will be persisted based on references held by the owning side of the relationship. It is the developer’s responsibility to keep the in-memory references held on the owning side and those held on the inverse side consistent with each other when they change. In the case of unidirectional one-to-one and one-to-many relationships, it is the developer’s responsibility to insure (sic) that the semantics of the relationships are adhered to.[29]

    It is particularly important to ensure that changes to the inverse side of a relationship result in appropriate updates on the owning side, so as to ensure the changes are not lost when they are synchronized to the database.

like image 194
Glen Best Avatar answered Oct 21 '22 06:10

Glen Best