Search code examples
javaspringthymeleaf

Using a conditional expression in thymeleaf aggregates.sum


I have a class Task which holds a list of bookings.

public class Task extends BaseTask {
    @ManyToOne
    private User assignee;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "task")
    private List<Booking> times = new ArrayList<>();

}


public class Booking {
    @ManyToOne(optional = false)
    private User user;
    @ManyToOne(optional = false)
    private Task task;
    private int timeSpent;
}

In the controller I add the task and the user which is currently logged in to the model.

@GetMapping("/viewTask/{taskId}")
    public String viewTask(@PathVariable("taskId") Long taskI, Model model) 
        model.addAttribute("task", taskService.findById(taskId));
        model.addAttribute("userObject", userService.findCurrentUser());
    }

Now I want calculate how much time the currently logged in user has already booked on the task object. To do so I´d like to use thymeleafs aggregates.sum function.

This statement adds up the timeSpent of ALL bookings.

th:text="${#aggregates.sum(task.times.![timeSpent])} + ' hours'"

But I ONLY want to add the timeSpent if the booking belongs to the currently logged in user. If I hard code the name of the user (unique) to check if the booking belongs to him, it works as well.

th:text="${#aggregates.sum(task.times.?[user.getName() == 'sandra'].![timeSpent])} + ' hours'"

But if I try to use the model attribute for the condition like so:

th:text="${#aggregates.sum(task.times.?[user == ${userObject}].![timeSpent])} + ' hours'"
or
th:text="${#aggregates.sum(task.times.?[user == __${userObject}__].![timeSpent])} + ' hours'"

I get the following exception:

Property or field 'sandra' cannot be found on object of type 'de.hsba.bi.projectwork.booking.Booking' - maybe not public or not valid?

If I try comparing the ids like this:

th:text="${#aggregates.sum(task.times.?[user.id == ${userObject.id}].![timeSpent])} + ' hours'"
th:text="${#aggregates.sum(task.times.?[user.getId() == ${userObject.getId()}].![timeSpent])} + ' hours'"

This exception is thrown:

Expression [#aggregates.sum(task.times.?[user.id == ${userObject.id}].![timeSpent])] @41: EL1043E: Unexpected token. Expected 'rsquare(])' but was 'lcurly({)'

Does someone know what I´m doing wrong?


Solution

  • I fixed the issue by first declaring a thymeleaf-variable like so:

    th:with="userId = ${userObject.getId()}"
    

    and then doing the comparison like so

    th:text="${#aggregates.sum(task.times.?[user.id == __${userId}__].![timeSpent])} + ' hours'"
    

    In the end my html looks like this:

    <td th:with="userId = ${userObject.getId()}">
    <b th:text="${#aggregates.sum(task.times.?[user.id == __${userId}__].![timeSpent])} + ' hours'"></b>
    </td>