Search code examples
hibernatecriteria

How do you order a oneToMany join table in hibernate criteria


Say I have a class Mother with a oneToMany mapping to Kittens

@Entity
@org.hibernate.annotations.Entity(dynamicUpdate = true)
@Table(name = "Mother")

.....

@OneToMany(fetch = FetchType.LAZY, targetEntity=Kittens.class, cascade=CascadeType.ALL)
@JoinColumn(name="motherId")
private List<Kittens> kittens;

I am using the criteria Api to provide a list

Criteria criteria = this.getSession().createCriteria(Mother.class);
Criterion MotherType = Restrictions.eq("type", "domesticated");
criteria.add(MotherType)
.addOrder(Order.asc("motherName"))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
.setFetchMode("kittens", FetchMode.JOIN)
// .addOrder(Order.asc("kittens.kittenName"));
List test = criteria.list();

Works fine until I try to add the order of the kittens field kittenName

I've also tried adding the @OrderBy(value="kittenName") annotation under the Kitten @OneToMany(...etc ) which works fine until you use the criteria API and this order will precede any other order statements in the sql.

Cheers in advance for any help...


Solution

  • You need to add the @javax.persistence.OrderBy annotation to your kittens list.

    @OneToMany(fetch = FetchType.LAZY,
               targetEntity=Kittens.class,
               cascade=CascadeType.ALL)
    @JoinColumn(name="motherId")
    @OrderBy("kittenName")
    private List<Kittens> kittens;
    

    @See