0

Is there a way to return the size of a collection via rest api projection?

Consider this example:

The data:

@Entity
@Table
public class MyData {
    // id 
    // ...

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "mydata")
    private final Set<User> users = new HashSet<>();
    // getters/setters ...
}

the repository:

@RepositoryRestResource
public interface MyDataRepository extends PagingAndSortingRepository<MyData, Long> {
}

the projection:

@Projection(name = "short", types = {MyData.class})
public interface MyDataProjection {
    // neither of those work
    // @Value("#{target.getUsers().size()}")
    @Value("#{target.users.size()}")
    Integer nrUsers();
}

I want to get the number of Users in a MyData-Object returned via REST api.

For example: my-domain/my-service/mydatas/123/?projection=short

should return:

{
    "nrUsers": 4;
    ...
}

Is it possible anyway?

sotix
  • 822
  • 1
  • 8
  • 23

1 Answers1

1

The naming convention ist to start with a "get" since the attributes of the projection are methods, not fields. So this works:

@Value("#{target.users.size()}")
Integer getNrUsers();

(instead of the previous "nrUsers()")

sotix
  • 822
  • 1
  • 8
  • 23