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
ExamTask
extends ExamObject
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;
...
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.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With