Home > OS >  Sprint JPA - Sorting by other table's column
Sprint JPA - Sorting by other table's column

Time:05-11

Please check the following case:

class ParentClass {

    List<ChildClass> children;

}

class ChildClass {}

class SortingClass {}

Basically, ParentClass has a @OneToMany relation with ChildClass, while ChildClass could be joined (@ManyToMany) with SortingClass in order to sort ChildClass objects inside the ParentClass once returned to the caller.

In the very end, ParentClass should have ChildClass items sorted by a specific SortingClass attribute, which shall not be included in the ResultSet given back to the caller.

i.e. ChildClass is a DATE item (start, end, process, etc.), while SortingClass states that the START DATE item shall come before the END DATE one when positioning those two items in the final front-end view.

How could I achieve this with Spring/Repository JPA annotations? Shall I move this sorting to the front-end application, having both information (parent/child and sorting) as separated?

Thank you.

Regards, A.M.

CodePudding user response:

You can use @OrderBy to achieve this:

class ParentClass {

    @OrderBy("fieldName ASC")
    List<ChildClass> children;

}

CodePudding user response:

Assuming that the classes are composed in this way:

class ParentClass {
    private long id;
    private List<ChildClass> children;

}

class ChildClass {
    private SortingClass fieldName
}

class SortingClass {
    private LocalDate start;
}

A Spring Data Repository can be created with these methods:

@Repository
class ParentRepository extends JpaRepository<ParentClass, Long> {

    Optional<ParentClass> findByIdOrderByChildrenFieldNameStartAsc(long id);
    
    List<ParentClass> findAllOrderByChildrenFieldNameStartAsc();

}
  • Related