Search code examples
hibernatejoincriteria

hibernate criteria: get a specific class


Assume the following classes model: (written from memory)

@Entity
@Table(name="BULLETIN_MESSAGE")
public class BulletinMessage { 
   @OneToMany
   @JoinColumn(name="BULLETIN_ID")
   private List<MeteoMessage> messages;  
}

@MappedSuperclass
public abstract class MeteoMessage {
    private String firLocation;
}

@Entity
@Table(name="METAR_MESSAGE")
@PrimaryKeyJoinColumn(name="metar_id")
public class MetarMessage extends MeteoMessage {
}

@Entity
@Table(name="AIRMET_MESSAGE")
@PrimaryKeyJoinColumn(name="airmet_id")
public class AirmetMessage extends MeteoMessage {
}

I would like to get all AftnMessages joined with MetarMessages from particular firLocation. But when I try to write:

Criteria criteria = session.createCriteria(BulletinMessage.class, "bulletin").createAlias("messages", "meteo", JoinType.LEFT_OUTER_JOIN);
criteria.add(Restrictions.eq("meteo.firLocation", "EPWA"));

I get the following sql:

select ... from BULLETIN_MESSAGE b 
LEFT OUTER JOIN AIRMET_MESSAGE a on ....
LEFT OUTER JOIN METAR_MESSAGE m on ...
WHERE a.firLocation = ?   

Note that the hibernate has chosen an AIRMET_MESSAGE in' where' expresion. How to force the hibernate to chose a METAR_MESSAGE in 'where' expresion:

WHERE m.firLocation = ?


Solution

  • MeteoMessage must be an entity, and thus be annotated with @Entity, and not with @MappedSuperclass, to be able to create an association to it.

    Then you should be able to use

    criteria.add(Restrictions.eq("meteo.class", MetarMessage.class));