Search code examples
hibernatejpahibernate-mappinghibernate-onetomany

Hibernate OneToMany selects all child instances for every parent instances


i have two classes associated with OneToMany - ManyToOne mapping. When i select parent Entity it selects Child entity also but, all child instances assigned to it's every parent instances instead of assign related instances.

PurchaseEntry.java

@Entity
@Table(name="PURCHASE_ENTRY")
public class PurchaseEntry {

    public PurchaseEntry() {
    }
    @Id @Column(name="PURCHASE_ID") @GeneratedValue(strategy=GenerationType.AUTO)
    private long purchaseId;
    @Column(name="INVOICE_NO")
    private String invoiceNo;
    @Column(name="INVOICE_DATE")
    @Type(type="date")
    private Date invoiceDate;          

    @OneToMany(targetEntity=PurchaseDetails.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    @JoinColumn(name="PURCHASE_ID")
    private Collection<PurchaseDetails> purchaseDetailsList = new ArrayList<PurchaseDetails>(); 
}

PurchaseDetails.java

@Entity
@Table(name = "PURCHASE_DETAILS")
public class PurchaseDetails {

    public PurchaseDetails() {
    }

    @Id
    @Column(name = "PURCHASE_DETAIL_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long purchaseDetailId;
    @Column(name = "AMOUNT")
    private float amount;    

    @ManyToOne
    @JoinColumn(name = "PURCHASE_ID")
    private PurchaseEntry purchaseEntry;

}

when saving PurchaseEntry.java object with PurchaseDetails.java instance Collection it works fine but while selecting parent table it selects related child table rows but this related all rows are assigned for every parent class object

select query

Criteria criteria = session.createCriteria(PurchaseEntry.class)
                    .add(Restrictions.between("invoiceDate", fromFilterDate, toFilterDate)).addOrder(Order.asc("invoiceDate"));

            purchaseEntryList = criteria.list();

for example Purchase_Entry table has row with

purchase_id - 1, invoice_date - 18-07-2014

and Purchase_details table has

PURCHASE_DETAIL_ID - 1, purchase_id - 1, ...

PURCHASE_DETAIL_ID - 2, purchase_id - 1, ...

PURCHASE_DETAIL_ID - 3, purchase_id - 1, ...

when i select PurchaseEntry using criteria where invoice_date '18-07-2014' it returns 3 PurchaseEntry objects, in every PurchaseEntry objects purchaseDetailsList has 3 PurchaseDetails objects related with purchase_id = 1

what's wrong with my configuration or any other???

expected : every PurchaseEntry objects has only one related PurchaseDetails instance in purchaseDetailsList


Solution

  • Unfortunately i found ans for this by using below code

    @OneToMany(cascade=CascadeType.ALL) 
        @JoinColumn(name="PURCHASE_ID")
        @Fetch(FetchMode.SELECT)
        private Collection<PurchaseDetails> purchaseDetailsList = new ArrayList<PurchaseDetails>();
    

    adding @Fetch(FetchMode.SELECT) working as i expected also i had recreate my schema