Spring Data REST - How to include calculated data in a projection?

Viewed 7208

I have the following domain classes defined.

Loan Class

@Data
@Entity
public class Loan {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String loanTitle;


    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "loan_id")
    private List<Allowance> allowances;
}

Allowance class

@Data
@Entity
public class Allowance {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private AllowanceType allowanceType;


    private Double allowanceAmount;

}

I also have a projection interface defined for the loan class as follows:

@Projection(name = "studyLoanSingle", types = {Loan.class})
public interface LoanProjection {

    String getLoanTitle();

    List<AllowanceProjection> getAllowances();

}

Now I want to include the total amount of the loan(which is calculated by iterating the list of Allowances) in the projection and send it to the UI. Is it possible to do this in Spring Data REST?

2 Answers

Place on domain objects methods to solve a view representation (projection) is not the best solution.

Place on repository would be useful for simple use cases, for complex issues where Java 8 will be present thanks to default methods of interface you can use this simple trick.

@Projection(name = "studyLoanSingle", types = Loan.class)
public interface LoanProjection {

    String getLoanTitle();

    //If no need Allowances on json
    @JsonIgnore
    List<Allowance> getAllowances();

    public default Double getAmount() {
        Double result = new Double(0);
        for (Allowance a : getAllowances()) {
           result += a.getAllowanceAmount();            
        }
        return result;
    }
}
Related