Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Order by on one to many relationship with different child object type

Question

I need sort the ExamObjects according to the id if the ExamObject is of ExamTask and sort it according to the questionNumber if it's ExamQuestion. How can I do this?

Important

An exam will only have a set of ExamTask or ExamQuestion. In other words, one exam cannot have a mixture of ExamTask and ExamQuestion.

Background Information

I have an Entity class called Exam This class can contain one or more ExamObject entities.

@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 can be of two types as below using JOINED

  1. ExamTask extends ExamObject
  2. ExamQuestion which extends ExamObject and has a column called 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;
   ...
like image 840
Faraj Farook Avatar asked Apr 19 '15 13:04

Faraj Farook


2 Answers

I believe your issue is that you are using a Set in your entity. A Set will not maintain order. When your relationship is loaded the set will not guarantee insertion order. Try using a List instead. The List will maintain the insertion order.

@Entity
public class Exam {
   @OneToMany(mappedBy = "exam" ...)
   @OrderBy("id") //I need to order this by question number if its ExamQuestion
   private List<ExamObject> objects;
   ...
}

Hope that helps.

like image 135
Paul Lungu Avatar answered Sep 29 '22 11:09

Paul Lungu


I used @OrderBy with Set and it works fine.

@OneToMany(mappedBy = "mailing", fetch = FetchType.LAZY)
@OrderBy("documentPrintOrder ASC")
private Set<MailingDocsEntity> mailingDocs = new HashSet<MailingDocsEntity>();
like image 33
Mia Avatar answered Sep 29 '22 13:09

Mia