1、实体类
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import org.appdot.model.IdEntity;
@Table(name = "tw_media")
@Entity
public class Media extends IdEntity implements Comparable<Media> {
protected String url;
protected MediaType mediaType;
protected Integer displayOrder;
@Column(name = "url")
public String getUrl() {
return url;
}
@Enumerated(EnumType.STRING)
@Column(name = "media_type")
public MediaType getMediaType() {
return mediaType;
}
@Column(name = "display_order")
public Integer getDisplayOrder() {
return displayOrder;
}
public void setUrl(String url) {
this.url = url;
}
public void setMediaType(MediaType mediaType) {
this.mediaType = mediaType;
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Media [url=").append(url).append(", mediaType=").append(mediaType).append(", displayOrder=")
.append(displayOrder).append("]");
return builder.toString();
}
public static enum MediaType {
IMAGE
}
@Override
public int compareTo(Media o) {
Integer otherDisplayOrder = o.displayOrder;
if (otherDisplayOrder == null) {
return 1;
}
if (displayOrder == null) {
return -1;
}
return displayOrder.compareTo(otherDisplayOrder);
}
}
2、取出实体集合后需要调用sort()
***********代码片段***********
Set<Media> medias = company.getImages();
List<Media> tmpList = new ArrayList<Media>();
Iterator<Media> iterator = medias.iterator();
while (iterator.hasNext()) {
Media tmp = iterator.next();
tmpList.add(tmp);
}
Comparator<Media> mycmp = ComparableComparator.getInstance();
//默认升序
//mycmp = ComparatorUtils.reversedComparator(mycmp); // 逆序
Comparator cmp = new BeanComparator("displayOrder", mycmp);
Collections.sort(tmpList, cmp);