0

I'm trying to associate 2 classes as below

the code sample for description is as below Bill Class

public class Bill {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO )
    private long id;
    private long billNumber;
    private BillType billType;
    @OneToOne
    private Customer billCustomer;

//getter and setter omitted
}

and definition of customer class is

public class Customer {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String customerRef;
    @OneToMany(fetch = FetchType.EAGER)
    private List<Bill> customerBills;}

when i try to retrive the object with criteria API, the associated objects are retrived.

Bill bill = (Bill) session.createCriteria(Bill.class)
                .add(Restrictions.eq("billNumber", BILL_NUMBER)).uniqueResult();

when i validate the size of the bills associated with an customer, it retrived as null. (but 1 bill is associated to customer)

Assert.assertEquals(1,bill.getBillCustomer().getCustomerBills().size());

(the above condition fails), but when i validate with other way around, it succeeds

List<Bill> billList = session.createCriteria(Customer.class)
                .add(Restrictions.eq("customerRef",CUSTOMER_REF)).list();
        Assert.assertEquals(1,billList.size());

I eagerly loaded the objects. i can't figure out what i'm missing?

1 Answer 1

1

Your mapping is wrong. If the association is a one-to-many bidirectional association, one side must define it as OneToMany, and the other side as ManyToOne (not OneToOne).

Moreover, a bidirectional association always has an owner side and an inverse side. The inverse side is the one with the mappedBy attribute. In the case of a OneToMany, the inverse side must be the one side. So the mapping should be:

@ManyToOne
private Customer billCustomer;

...

@OneToMany(fetch = FetchType.EAGER, mappedBy = "billCustomer")
private List<Bill> customerBills;

This mapping is described in the hibernate documentation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.