HIbernate Annotations - criteria query - loading lazy properties fail

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?

Answers


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.


Need Your Help

Android onDraw() is not getting called on Timer

android android-canvas

This is in GraphView.java which extends View. I want that when this invalidate(bounds) is getting called, at the same time it should call onDraw().. What is bug in this code. It is giving me this

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.