Hibernate Crtieria and Restrictions not working correctly

1.8k views Asked by At

I have an object within an object and want to create a restriction using one of the fields within the inner most object. Now i figured it could be achieved by doing something like:

... .add(Restrictions.eq("myObjectTwp.myObjectThree.myObjectsID", mySearchId)).list();

However this does not seem to work. However, I get no error message and instead it almost looks like this restriction has not been taken into account.

2

There are 2 answers

0
JB Nizet On BEST ANSWER

You need to make a join. In the criteria API, the easiest way to do that is to use the createAlias() method:

session.createCriteria(Child.class, "child")
       .createAlias("child.parent", "theParent")
       .add(Restrictions.eq("theParent.someField", theFieldValue))
       .list();

This query is equivalent to the following HQL:

select child from Child child
inner join child.parent theParent
where theParent.someField = :theFieldValue
3
Raffaele Rossi On

I think it would help if you shared your mapping file (or annotations).

For example in my project I have the following:

<hibernate-mapping>
    <class name="Client" table="Client">
    ...
    <many-to-one name="user" class="User" column="idUser"/>

And

<hibernate-mapping>
    <class name="User" table="User">
    <property name="email" type="string"/>

Reading at the hiberante documentation http://docs.jboss.org/hibernate/core/4.0/manual/en-US/html/querycriteria.html#querycriteria-associations if I'd like to query the clients related to a specific user's email (merging JB Nizet's comment):

List clients = sess.createCriteria(Client.class)
                   .createAlias("user", "u")
                   .add(Restrictions.eq("u.email", "[email protected]"))
                   .list();

I'm not sure anyway.