ipavlic
ipavlic

Reputation: 4956

Hibernate criteria for many-to-one mapped column

Suppose I have mappings set-up like this; there are CodeType rows in the database, and there are also Code rows in a code table. Each Code can be of a certain code-type.

<class name="CodeType" table="CODE_TYPE">
    <id name="id" column="ID">
        <generator class="org.hibernate.id.MultipleHiLoPerTableGenerator">
            <param name="max_lo">100</param>
        </generator>
    </id>
    <property name="name" column="NAME"></property>
    <property name="description" column="DESCRIPTION"></property>
    <property name="version" column="VERSION"></property>
</class>

And here are the codes. As many codes can be of the same type, many-to-one is defined.

<class name="Code" table="CODE">
<id name="id" column="ID">
    <generator class="org.hibernate.id.MultipleHiLoPerTableGenerator">
        <param name="max_lo">100</param>
    </generator>
</id>
<property name="name" column="name"></property>
<many-to-one name="codeType" class="CodeType" column="CODE_TYPE_ID"></many-to-one>
<property name="version" column="VERSION"></property>

I would need to find those codes that have a certain type. How can I do that? If I hadn't set codeType as a many-to-one, and instead kept it as just a Integer, I could easily write something like .add( Restrictions.eq("codeTypeId", 42)).

Upvotes: 1

Views: 2183

Answers (1)

Firo
Firo

Reputation: 30813

Restrictions.eq("codeType.id", 42)

or

Restrictions.eq("codeType", session.load<CodeType>(42))

Upvotes: 1

Related Questions