Is there a way to sort an entity and its nested collection in a @OneToMany relationship with a Pageable interface?
I have these two entities
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "course")
private List<Review> reviews = new ArrayList<>();
....contructors, getters and setters
}
@Entity
@Table(name = "review")
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String rating;
@ManyToOne
private Course course;
....contructors, getters and setters
}
This repository
@Repository
public interface CourseRepository extends JpaRepository<Course, Long> {
}
This service
@Service
public class CourseService {
@Autowired
CourseRepository courseRepository;
public Page<Course> getCourses(Pageable pageable) {
return courseRepository.findAll(pageable);
}
}
And this controller
@RestController
@RequestMapping("/api")
public class CourseController {
@Autowired
CourseService courseService;
@RequestMapping(value="/courses", method= RequestMethod.GET)
public ResponseEntity<Page<CourseDTO>> readInteractionsPagedParam(Pageable pageable) {
Page<Course> pageCourse = courseService.getCourses(pageable);
... To DTO and return it
}
}
I found other similar questions but in the answers the sorting become static, like @OrderBy annotation but the need is that the sorting will be dynamic, I mean, I must order by any property in course and review. I must use Pagable too.
I need something like these but I tried them and only sort the entity Course, the entity Review never is sorted
.../api/courses?page=0&size=10&sort=name,asc&sort=reviews.rating,asc
.../api/courses?page=0&size=10&sort=name,asc&sort=reviews.rating,desc
.../api/courses?page=0&size=10&sort=name,desc&sort=reviews.rating,asc
.../api/courses?page=0&size=10&sort=name,desc&sort=reviews.rating,desc
I new in all of this, Java, Spring, JPA, Hibernate, etc and I would like to know if is there a way to achieve this?