简体   繁体   中英

how to apply filter on composite-id key property in hibernate

I am trying to resolve an issue related to filtering in hibernate, specially when dealing with composite Id's

I have a AttrDesc.hbm.xml

<hibernate-mapping>
    <class name="AttrDesc" table="ATTRDESC">
        <composite-id>
            <key-property name="attr_id" type="long"/>
            <key-property name="language_id"/>
        </composite-id>
        <property name="attrtype_id"/>
        <property name="name"/>
        <property name="description"/>
        <property name="description2"/>
        <property name="field1"/>
        <property name="groupname"/>
        <property name="qtyunit_id"/>
        <property name="noteinfo"/>
        <filter name="langFilter" condition=":langid=language_id"/>
    </class>
     <filter-def name="langFilter">  <filter-param name="langid" type="int"/>   </filter-def>
</hibernate-mapping>

Issue: I am unable to apply filter on the language_id which is part of composite-id

while debugging I found that the filter-param langid is some how has value as 0 where as actual value that I set using below line of code is -1

session.enableFilter("langFilter").setParameter("langid", -1);

Note: that works if I move language_id out of the composite-id

any help is appreciated, Thanks

For Hibernate jpa 2.1 and above you should modify the mapping a little.

<composite-id name="attrDescId" class="AttrDescId">
    <key-property name="attr_id" type="long"/>
    <key-property name="language_id"/>
</composite-id>

Accordingly, you will need to change the model class to be

public class AttrDesc {
    AttrDescId id;
    String name;
    //other fields
}
public class AttrDescId {
    long attr_id;
    String language_id;
}

And then with root.get("attrDescId").get("language_id") you will be able to put filter on language_id . Elaborately,

CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<AttrDesc> query = builder.createQuery(AttrDesc.class);
Root<AttrDesc> root = query.from(AttrDesc.class);
query.select(root).where(builder.equal(root.get("attrDescId").get("language_id"), "the filter value"));
Query<AttrDesc> q = sessionFactory.getCurrentSession().createQuery(query);
List<AttrDesc> attrDescList = q.getResultList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM