Search code examples
hibernatecriteria

org.hibernate.QueryException: not an association


I want to add an order by restriction to a criteria in Hibernate. I have two tables Event and MainEvent with the relation One To Many (a MainEvent has many Events).

    final Criteria criteria = getCurrentSession().createCriteria(
            Event.class);
    criteria.createAlias("mainEvent.date", "deadline");
    criteria.addOrder(Order.asc("deadline"));
    return criteria.list();

When I try to run this it gives me the following error:

org.hibernate.QueryException: not an association: date.

MainEvent entity:

@Entity
@Table(name = "MAIN_EVENT")
public class MainEventEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "MAIN_EVENT_ID")
    private int id;

    @Column(name = "MAIN_EVENT_DATE")
    private Date date;

    @OneToMany(mappedBy = "mainEvent", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<EventEntity> events = new ArrayList<EventEntity>();

}

Event entity:

@Entity
@Table(name = "EVENT")
public class EventEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "EVENT_ID")
    private int id;

    @ManyToOne(cascade = CascadeType.PERSIST)
    @JoinColumn(name = "MAIN_EVENT_ID", nullable = false)
    private MainEventEntity mainEvent;

}

Solution

  • As per the API for Criteria.createAlias, you can create alias only for associations not for the fields of an association.

    createAlias
    
    Criteria createAlias(String associationPath,
                         String alias)
                         throws HibernateException
    Join an association, assigning an alias to the joined association.
    
    
    
    Parameters:
    associationPath - A dot-seperated property path
    alias - The alias to assign to the joined association (for later reference).
    Returns:
    this (for method chaining)