Home > Net >  How to get an average int for a Collection of an Entity using thymeleaf?
How to get an average int for a Collection of an Entity using thymeleaf?

Time:10-02

I have an Employee Entity that has a Collection of Reviews, each Review has a byte grade.

Unnecessary details are omitted for brevity

@Entity
public class Employee extends AbstractBaseEntity {
    @OneToMany( mappedBy = "employee",  cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    private List<Review> reviews;
}
@Entity
public class Review extends AbstractBaseEntity {
    private Byte grade;
}

How can I get an average Review grade for each Employee using Thymeleaf to insert in Table?

CodePudding user response:

Best would be to add the corresponding method to the class:

@Entity
public class Employee extends AbstractBaseEntity {
    @OneToMany( mappedBy = "employee",  cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    private List<Review> reviews;

    public double getAverage() {
        return reviews.stream().map(Review::getGrade).mapToInt(Byte::intValue).average()
    }
}

and then just call it in thymeleaf

<span th:text="${employee.getAverage()}" />

CodePudding user response:

Thymeleaf has aggregate functions. You can combine them with collection projection.

<span th:text="${#aggregates.avg(employee.reviews.![grade])}" />
  • Related