polmarex
polmarex

Reputation: 1383

Making join with Criteria

I'm terribly new to Hibernate. I've googled for two hours but I still can't figure out, how to make JOIN without using HQL, only by criteria. I have tables Clients(cID, name) and Visits(vID, vcID, date). The relation is one to many (one client can visit multiple times). I would also like to do it without setFetchMode. Just Criteria. Do I have to change the mappping xml?

UPDATE: this is part of my mapping xml:

 <class name="Client" table="Clients">
   <id name="cID" column="cID"><generator class="native"/></id>
   <property name="name"     length="10" not-null="true"/>
 </class>
 <class name="Visit" table="Visits">
   <id name="vID" column="vID"><generator class="native"/></id>
   <property name="vcID"     length="10" not-null="true"/>
   <property name="date" length="25" not-null="true"/>
 </class>

Upvotes: 0

Views: 322

Answers (2)

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

You need to update you mapping:

 <class name="Client" table="Clients">
   <id name="cID" column="cID"><generator class="native"/></id>
   <property name="name"     length="10" not-null="true"/>
   <!-- Declare Set<Visit> visits in the Client class-->
   <set name="visits" lazy="false" cascade="all">
        <key column="vcID"/>
        <one-to-many class="your.package.Visit"/>
    </set>
 </class>
 <class name="Visit" table="Visits">
   <id name="vID" column="vID"><generator class="native"/></id>
   <!-- and add "Client client" property to your Visit class --> 
   <many-to-one name="client" column="vcID" lazy="false"/> 
   <property name="date" length="25" not-null="true"/>
 </class>

Then:

 Criteria criteria = session.createCriteria(Visit.class).addCriteria("client")
                      .add(Restriction.eq(...));

or

Criteria criteria = session.createCriteria(Client.class).addCriteria("visits")
                      .add(Restriction.eq(...));

And Hibernate will join them automatically.

Upvotes: 1

PepperBob
PepperBob

Reputation: 707

Having a class Client with a list-attribute "visits" that's mapping to your Visit-Entity:

Criteria criteria = session.createCriteria(Client.class);
criteria.addCriteria("visits");

This would create an inner join between your client-table and your visits-table.

Update:

Here you'll find some good examples: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html#querycriteria-associations

Mapping Example

I hardly ever use hibernate mapping xml, however it should read similiar to:

   <class name="Client" table="Clients">
      <id name="cID" column="cID"><generator class="native"/></id>
      <property name="name"     length="10" not-null="true"/>

      <bag name="visits">
           <key column="vcId"/>
           <one-to-many class="Visit"/>
      </bag>
    </class>

Tell Hibernate that there is a property "visits" which represents a one-to-many relationship.

Upvotes: 3

Related Questions