Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 635
jaseFace Avatar asked Apr 06 '11 00:04

jaseFace


People also ask

What is join table in hibernate?

When a join table is used in mapping a relationship with an embeddable class on the owning side of the relationship, the containing entity rather than the embeddable class is considered the owner of the relationship. If the JoinTable annotation is missing, the default values of the annotation elements apply.

What is difference between mappedBy and @JoinColumn?

The @JoinColumn annotation helps us specify the column we'll use for joining an entity association or element collection. On the other hand, the mappedBy attribute is used to define the referencing side (non-owning side) of the relationship.


1 Answers

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

  • Hibernate Annotations Reference Guide
  • Chapter 2.2.5. Mapping entity associations/relationships
  • Subchapter 2.2.5.3.4. Indexed collections (List, Map)
like image 116
Ralph Avatar answered Nov 05 '22 07:11

Ralph