就像马科斯·弗拉格卡基斯说的那样
不幸的是,映射中的排序(或@OrderBy)优先,这使得标准设置的排序变得毫无用处。
但是,如果要对 Set 进行排序,则必须设置@Order。
你仍然可以使用 HQL 代替 (在休眠 3.3.2.GA 测试 ),他们首先按 hql 查询中的顺序排序:
@Entity
@Table(name = "Person")
public class Person {
@Id
@Column(name = "ID_PERSON", unique = true, nullable = false, precision = 8, scale = 0)
private Long id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "person")
@OrderBy
private Set<Book> books = new HashSet<Book>(0);
public Person() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Set<Book> getBooks() {
return this.books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
}
/**
* hql Version
*
* Result in :
* order by
* book1_.TITLE asc,
* book1_.ID_BOOK asc
**/
@Override
public Person getFullPerson(Long idPerson) {
StringBuilder hqlQuery = new StringBuilder();
hqlQuery.append("from Person as p ");
hqlQuery.append("left join fetch p.books as book ");
hqlQuery.append("where p.id = :idPerson ");
hqlQuery.append("order by book.title ");
Query query = createQuery(hqlQuery.toString());
query.setLong("idPerson", id);
return uniqueResult(query);
}
/**
* criteria Version // not usable
*
* Result in :
* order by
* book1_.ID_BOOK asc,
* book1_.TITLE asc
**/
@Override
public Person getFullPersonCriteria(Long idPerson) {
Criteria criteria = ...
criteria.add(Restrictions.eq("id", idPerson));
criteria.createAlias("books", "book", CriteriaSpecification.LEFT_JOIN);
criteria.addOrder(Order.asc("book.title"));
return criteria.uniqueResult();
}