How to display a collection with multiple id's?

541 views Asked by At

I have a collection of people with id's assigned to them. I want the user to have the Ability to retrieve people collection using multiple ID's ( 0 to many).I can do this if I have one id as the parameter:

@Path( "{people/id}" )
@GET
public PeopleDTO findOne ( @PathParam( "id" ) int id ) {
    return PersonDAO.findOne( id );
}

How do I write a similar method where user can specify multiple id's and that will retrieve info for that many people? Or to say it differently, I want to output collection of people accepting filter for 0...* IDs.

1

There are 1 answers

0
Paul Samsotha On

Since you are not trying to access a single resource, then you are trying to access the collections of resources, only you just want a subset. This is pretty common for things like pagination. For that you can just have a query parameter to filter. For instance you can use

.../people?filterIds=1,3,5,6,7,8

Then just use @QueryParam

@GET
@Path("people")
public PeopleDTO getPeople(@QueryParam( "filterIds" ) String id ) {

This can be used to get all the people or a filtered list. You just need to parse the string. First check if it's null, if it is, then it's a request for a full list.

You could also may it more object oriented, and use something like Filtered

@GET
@Path("people")
public PeopleDTO getPeople(@QueryParam( "filterIds" ) Filtered filtered ) {
    String[] values = filtered.getValues();

You can take a look at this to see that can be accomplished. Use something like

public class Filtered {

    private String[] values;
    public String[] getValues() { return values; }
    public void setValues(String[] values) { this.values = values; }

    public static Filtered fromString(String param) {
        if (param == null) return null;

        Filtered filtered = new Filtered();
        filtered.setValues(param.split(",");
        return filtered;
    }
}