问题
如果id
是ExamObject
,则需要根据ExamTask
排序ExamObjects;如果是questionNumber
,则需要根据ExamQuestion
对其排序。我怎样才能做到这一点?
重要
考试只有一组ExamTask
或ExamQuestion
。换句话说,一个考试不能同时包含ExamTask和ExamQuestion。
背景信息
我有一个名为Exam
的Entity类,该类可以包含一个或多个ExamObject
实体。
@Entity
public class Exam {
@OneToMany(mappedBy = "exam" ...)
@OrderBy("id") //I need to order this by question number if its ExamQuestion
private Set<ExamObject> objects;
...
}
ExamObject
可以使用JOINED
分为以下两种类型ExamTask
扩展了ExamObject
ExamQuestion
扩展了ExamObject
并具有称为questionNumber
的列ExamObject
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class ExamObject {
@Id
private Long id;
...
ExamTask
@Entity
@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
public class ExamTask extends ExamObject{
...
ExamQuestion
@Entity
@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
public class ExamQuestion extends ExamObject{
@Column(name = "question_number")
private Integer questionNumber;
...
最佳答案
通过声明集合为TreeSet
类型并向构造函数提供Comparator
,插入的项目将自动排序。
new TreeSet<ExamObject>(new Comparator<ExamObject>(){
@Override
public int compare(ExamObject a, ExamObject b){
int q1 = 0, q2 = 0;
if(a instanceof ExamQuestion){
q1 = ((ExamQuestion)a).questionNumber;
if(b instanceof ExamQuestion){
q2 = ((ExamQuestion)b).questionNumber;
}else{
q2 = ((ExamTask)b).id;
}
}else{
q1 = ((ExamTask)a).id;
if(b instanceof ExamQuestion){
q2 = ((ExamQuestion)b).questionNumber;
}else{
q2 = ((ExamTask)b).id;
}
}
if(q1 == q2) return 0;
else return q1 < q2 ? -1 : 1;
}
});