views:

526

answers:

1

enter code hereI want to apply restrictions on the list of items, so only items from a given dates will be retrieved.

Here are my mappings:

    <class name="MyClass" 
            table="MyTable" mutable="false" >
            <cache usage="read-only"/>
    <id name="myId" column="myId" type="integer"/>
    <property name="myProp" type="string" column="prop"/>
    <list name="items" inverse="true" cascade="none">
     <key column="myId"/>
     <list-index column="itemVersion"/>
     <one-to-many class="Item"/>
    </list> 
   </class>
    <class name="Item" 
            table="Items" mutable="false" >
            <cache usage="read-only"/>
    <id name="myId" column="myId" type="integer"/>
    <property name="itemVersion" type="string" column="version"/>
    <property name="startDate" type="date" column="startDate"/>
   </class>

I tried this code:

Criteria crit = session.createCriteria(MyClass.class);
crit.add( Restrictions.eq("myId", new Integer(1)));
crit = crit.createCriteria("items").add( Restrictions.le("startDate", new Date()) );

which result the following quires:

select ...
from MyTable this_ inner join Items items1_ on this_.myId=items1_.myId 
where this_.myId=? and items1_.startDate<=?

followed by

select ...
from Items items0_ 
where items0_.myId=?

But what I need is something like:

select ...
from MyTable this_ 
where this_.myId=?

followed by

select ...
from Items items0_ 
where items0_.myId=? and items0_.startDate<=?

Any idea how I can apply a criteria on the list of items?

A: 

You have two options here:
A) You can define a filter on "items" collection of MyClass:

<filter name="starDateFilter" condition="startDate <= :startDate"/>

You would then apply it by calling

session.enableFilter("startDateFilter").setParameter("startDate", new Date());

prior to retrieving your object. In this scenario you would only specify Criteria based on MyClass, not on Item (if you need Criteria at all, you can just use session.load() if all you need is id).

B) Set your items collection to lazy fetch. Query (or retrieve by id) your MyClass object, then create criteria based on Item alone (without linking to MyClass):

Criteria crit = session.createCriteria(Item.class);
crit.add( Restrictions.le("startDate", new Date()) );

This would return a list of Items (which, judging from your mapping don't have a link back to MyClass anyway). Option (B) would produce the SQL queries you're looking for.

ChssPly76