1. 程式人生 > >hibernate set、arrayList等排序問題

hibernate set、arrayList等排序問題

首先我們用hibernate做外來鍵關聯的時候常常會用到集合,但是在我們需要用到set的時候就頭疼了,set取出來的集合是無序的,但偏偏我需要用到有序的,

第一種方法就是,換,換成有序的集合不就行了,TreeSet、arrayList、sortedSet都是有序的

TreeSet;

  private  sortedSet<T> test=new TreeSet<T>();

省略getter、setter方法;

在配置檔案中

<set name="test"  sort="natural" lazy="false">
<key column="courseId" />
<one-to-many class="com.jxust.bean.Chapter"/>
</set>

ArrayList;

private List<T> test=new ArrayList<T>();

配置檔案中

<list name="test"  sort="natural" lazy="false">
<key column="courseId" />

                       <list-index column=" id"/>//用來排序的欄位,必須是你表中有的欄位
<one-to-many class="com.jxust.bean.Chapter"/>
</list>

第二種方法,set集合 ,       通過order by語句,相當於在HQL 語句中嵌入order by語句

private Set<T> test=new Set<T>();

配置檔案

<set name="test" order-by="id asc" lazy="false">
<key column="courseId" />
<one-to-many class="com.jxust.bean.Chapter"/>
</set>