Issue
I have an entity named Project
with a foreign Department
entity that has a name
field (See below):
@Entity
@Table(name = "project")
public class Project
{
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
@Type(type = "pg-uuid")
@Id
@Column(name = "project_id")
private UUID id;
@Column(nullable = false)
private String name;
@Column(nullable = true, unique = false)
private String description;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "department_id", nullable = false)
private Department department;
...
}
Then, in my ProjectService
class I have a method:
public Page<Project> findByFilterSort(final ProjectSearchDTO dto,
ProjectSortBy sortBy,
Direction direction,
int pageNumber,
int pageSize)
{
BooleanBuilder builder = createFilter(dto);
Sort sort;
switch (sortBy)
{
case NAME:
sort = new Sort(new Order(direction, "name"),
new Order(Direction.DESC, "created"));
break;
case DEPARTMENT_NAME:
???
...
}
PageRequest request = new PageRequest(pageNumber-1, pageSize, sort);
return projectRepository.findAll(builder, request);
}
Is there a way to sort the Department
by name
using this approach? If yes, how? If no, what is the best way?
Thanks in advance.
Solution
SOLVED:
I should have tried it. It's as simple as referencing the field with dot (.) operator. Wow.
case DEPARTMENT_NAME:
sort = new Sort(new Order(direction, "department.name"),
new Order(Direction.DESC, "created"));
Answered By - jetGeekster