hebingliu
hebingliu

Reputation: 13

How to sort on one of the composite keys in Hibernate using @OrderBy

I have two classes Course and Student. Student class use firstName and lastName as the composite-key. I want to use @OrderBy("firstName ASC") in Course class, but there is an error "property from @OrderBy clause not found: Student.firstName".

How can I sort on one of the composite keys (such as firstName)?

public class Course{
    @OneToMany(mappedBy="course")
    @OrderBy("firstName ASC")  
    // Error: property from @OrderBy clause not found: Student.firstName, why?
    private List<Student> students;
.....
}


public class Student{
    @Id
    @Column(name="first_name")
    private String firtName;
    @Id
    @Column(name="last_name")
    private String lastName;

    @ManyToOne
    @JoinColumn(name="course_id")
    private Course course;
.....
}

Upvotes: 1

Views: 2889

Answers (1)

Adeel Ansari
Adeel Ansari

Reputation: 39907

You misspelled it to, firtName -- notice s is missing. Fix that and things will be fine, most likely.

[Edited]

In case it is still not working. Try to replace this by @EmbeddedId, instead. Like below,

public class Student implements Serializable{
    @EmbeddedId
    private StudentPK name;

    @ManyToOne
    @JoinColumn(name="course_id")
    private Course course;
    .....

    @Embeddable
    public static class StudentPK implements Serializable {
        @Column(name="first_name")
        private String firtName;

        @Column(name="last_name")
        private String lastName;

        ....
    }
}

Then it should work using,

public class Course{
    @OneToMany(mappedBy="course")
    @OrderBy("name.firstName ASC")  
    private List students;
    .....
}

Upvotes: 1

Related Questions