wasp256
wasp256

Reputation: 6242

java hibernate criteria

I have the following table structure in my database:

 Table A:                     Table B:                       Table C:
 _______________________      ______________________________  ______________________
 | Field | Type | Key  |     | Field | Type | Key          |  | Field | Type | Key  |   
 ______________________|     |_____________________________|  |_____________________|
 | a_id  | Int  | PRI  |     | a_id  | Int  | FK of A(a_id)|  | c_id  | Int  | PRI  |
 |     ...       ...   |     | c_id  | Int  | FK of C(c_id)|  |       ...           |
 |_____________________|      ______________________________  |_____________________|

And the object:

  class A {
        List<C> list;
        ...
   }

Now I would like to receive an object A from the database with all C objects that are combined by the table B. I have the Criteria to receive the correct Object A but I don't know how to receive a List of the corresponding C Objects:

    Criteria crit = ...;
    A a = crit.uniqueResult();

Here is the SQL query that gives me the correct result and which should now be 'translated' in a Criteria:

 select c.* 
 from A as a, 
      B as b, 
      C as c 
 where a.a_id = b.a_id and b.c_id = c.c_id;

Does anyone know how to formulate the Criteria?

Upvotes: 0

Views: 219

Answers (1)

Raul Rene
Raul Rene

Reputation: 10280

If you have

class A {
    List<C> list;
    ...
}

and both A and C are @Entitys, your criteria would have to look like this:

// Create criteria on class A
Criteria criteria = session.createCriteria(A.class);

In this moment if you do a criteria.list() you will get all A objects, each with a list of C values for which you have only the ids. In order to bring the full C objects you need an extra :

criteria.createAlias("list", "listC");

This will create an alias for (i.e. inner join) A with C. Now, supposing you have an a (of class A) you can do a.getList().get(i).getWhateverFieldFromC(); so now you have for every instance of A its list of Cs populated.

Don't forget at the end to do a criteria.list() to retrieve the list. That would be all.

P.S. This is assuming (of course) that entities A and C are correctly mapped.

Upvotes: 1

Related Questions