问题

如果idExamObject,则需要根据ExamTask排序ExamObjects;如果是questionNumber,则需要根据ExamQuestion对其排序。我怎样才能做到这一点?

重要

考试只有一组ExamTaskExamQuestion。换句话说,一个考试不能同时包含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;
        }
    });
    

    09-28 05:16