项目当中需要用到对对象排序,而这时的对象已经装到list中。怎样进行排序呢?
1.将实体implements Comparable,并实现其comparaTo()方法
package com.itbbs.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import org.hibernate.annotations.Type;
@Entity
public class News implements Comparable<Object> {
private Category category;
private int clickNum;
private String content;
private Date date;
private int id;
private String img;
private String name;
private String title;
private int type;
private User user;
private Boolean headline;
public News() {
}
public News(int id, String title) {
super();
this.id = id;
this.title = title;
}
@ManyToOne
@JoinColumn(name = "categoryId", referencedColumnName = "id")
public Category getCategory() {
return category;
}
public int getClickNum() {
return clickNum;
}
@Lob
@Type(type = "text")
public String getContent() {
return content;
}
public Date getDate() {
return date;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
@Transient
public String getImg() {
return img;
}
public String getName() {
return name;
}
public String getTitle() {
return title;
}
public int getType() {
return type;
}
// 默认为eager 记住lazy
@ManyToOne
@JoinColumn(name = "userId", referencedColumnName = "id")
public User getUser() {
return user;
}
public void setCategory(Category category) {
this.category = category;
}
public void setClickNum(int clickNum) {
this.clickNum = clickNum;
}
public void setContent(String content) {
this.content = content;
}
public void setDate(Date date) {
this.date = date;
}
public void setId(int id) {
this.id = id;
}
public void setImg(String img) {
this.img = img;
}
public void setName(String name) {
this.name = name;
}
public void setTitle(String title) {
this.title = title;
}
public void setType(int type) {
this.type = type;
}
public void setUser(User user) {
this.user = user;
}
public void setHeadline(Boolean headline) {
this.headline = headline;
}
public Boolean getHeadline() {
return headline;
}
public int compareTo(Object o) {
News others = null;
if (o instanceof News) {
others = (News) o;
}
return this.type - others.type;
}
}
在项目中调用就很简单了。
List<News> tranfer = this.managerService.headline();
Collections.sort(tranfer);/* 排序 in type */