编程语言
首页 > 编程语言> > Java Order by与不同的子对象类型一对一关系

Java Order by与不同的子对象类型一对一关系

作者:互联网

如果ExamObject是ExamTask,则需要根据id对ExamObjects进行排序,如果是ExamQuestion,则需要根据QuestionNumber对其进行排序.我怎样才能做到这一点?

重要

考试只有一组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;
   ...
}

使用JOINED,ExamObject可以分为以下两种类型

> ExamTask扩展了ExamObject
> ExamQuestion,它扩展了ExamObject,并具有一个称为questionNumber的列

考试对象

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class ExamObject {    
    @Id
    private Long id;
    ...

考试任务

@Entity
@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id")
public class ExamTask extends ExamObject{
   ...

考试题

@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;
    }
});

标签:spring-data,jpa,hibernate,spring,java
来源: https://codeday.me/bug/20191120/2044140.html