Sanket Patel
Sanket Patel

Reputation: 259

Creating Hibernate Criteria Query for Tables with Multiple Relations

I've got a table structure something like this...

class A{
    Integer id;

    @OneToMany //
    List<B> b;

}

Class B{

    Integer id;

    @ManyToOne
    A a;

    @OneToMany
    List<C> c;
}

Class C{

    Integer id;

    String someField;

    @ManyToOne
    B b;

}

Now, I want to query all class A entries where C.someField equals to the parameter passed.

Note: There is no direct relation of A with C.

Relations are like A -> List < B > and B -> List < C > and I need to check it in the whole List of C.

How can I create criteria query for such a problem?

Upvotes: 1

Views: 550

Answers (2)

Sanket Patel
Sanket Patel

Reputation: 259

I've already changed my whole flow of implementation along with database structure, but if someone wants to implement a similar query, it can be done as below :

Criteria criteria = getCurrentSession().createCriteria(A.class,"a");
criteria.createCriteria("a.b",b);
criteria.createCriteria("b.c",c);
criteria.add(Restrictions.eq("c.someField","queryParameter");

What i was doing before was instead of criteria.createCriteria (Criteia on top of Criteria) i was using criteria.crateAlias (that only creates alias) for the lists.

Hope this help.

Upvotes: 0

Ravi Mengar
Ravi Mengar

Reputation: 1231

The query regarding your question be like,

SELECT c1.name, c1.id
FROM c c1
JOIN b b1 on c1.b_id = b1.id
JOIN a a1 on b1.a_id = a1.id
WHERE a1.name = 'ABC'

all class A entries where C.someField equals to the parameter passed like 'ABC'

Solution:

Criteria c_criteria = getCurrentSession().createCriteria(C.class,"c1"); 
Criteria b_criteria = c_criteria.createCriteria("b","b1");
Criteria a_criteria = b_criteria.createCriteria("c","c1");
a_criteria.add(Restrictions.eq("name", "ABC"));

ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("someField"));
properties.add(Projections.property("id"));

c_criteria.setProjection(properties);
c_criteria.list();

Upvotes: 2

Related Questions