ravinikam
ravinikam

Reputation: 3696

How to use join in hibernate criteria following situation

We have two tables Family and Member, the relation between these two is Family has set of members in it but member don't have any family relationship within it.

I wanted get member using dob and family for that I am using Hibernate criteria API's but I am not getting how to write join query since members don't have Family instance with it. So not able to use FetchMode. Any other way to achieve this ?

thanks in advance. - Ravi Nikam.

Upvotes: 1

Views: 3953

Answers (2)

ravinikam
ravinikam

Reputation: 3696

thank you guys, I have resolved this with one of my colleague as under

DetachedCriteria subquery = DetachedCriteria
            .forClass(Family.class, "family")
            .add(Expression.eq("family.id", family.getId()));

                subquery.createAlias("members", "members")
                    .add(Restrictions.eqProperty("members.id", "m.id"))
                    .add(Expression.eq("members.DOB",Date));

                subquery.setProjection(Property.forName("members.id"));

                Criteria crit = session.createCriteria(Member.class, "m")
                        .add(Subqueries.propertyIn("m.id", subquery));


            results = crit.list();

results has list of members i requested.

Upvotes: 1

sfussenegger
sfussenegger

Reputation: 36096

instead of trying to do

from Member m join m.family f where f.name = ?

which is not possible, you could do the exact opposite

select m from Family f join f.members m where f.name = ?

I know, it's HQL not Criteria, but that's what I'm more fluent with. It should be trivial to "translate" this HQL to Criteria though.

Upvotes: 1

Related Questions