简体   繁体   中英

Handling multiple values for a single query parameter in a rest webservice url and handling them using hibernate criteria

I have a rest web service which would accept 'name' and fetch the tokens from the db with this name and return the tokens back. The url for the rest webservice would be:

http://localhost:8080/NameService/Tokens?name=Bob

and in the serviceLayer, I have my method as follows:

@GET
@Path("Tokens")
@Produces("application/xml")
public JAXBElement<GetToken> getokenByName(@QueryParam("name") final String name ) {

    if(name!=null){
        // use hibernate criteria to fetch the records from db
        Criteria crit = getSession().createCriteria(getPersistentClass());
        crit.add(Restrictions.eq("name",name))
    }
}

Now we have a change in requirement when the client can send multiple names in the request at the same time.For example, give me the tokens where name = "bob" or "brendon" or "aaron" The URL could be like this:

http://localhost:8080/NameService/Tokens?name=Bob,Aaron,Brendon

The number of names sent is variable. It can be 1 or 2 or 3 so on. Any ideas on how to achieve this split and passing them to hibernate criteria as an OR condition in the service layer by tweaking the code shown above, which works for one name?

One way might be to use StringUtils to parse out the different names using delimiter (comma) and then form a list and some how adding the names in the list to criteria restrictions. But not sure if this works.

Any ideas?

Indeed the easiest way would be to split the query param using split(",") .

You can also set your query param to a List<String> and pass parameters like this:

http://localhost:8080/NameService/Tokens?name=Bob&name=Aaron&name=Brendon

Or you could also implement your own StringReaderProvider and register it to jersey.

For your comment: you should use a disjunction.

@GET
@Path("Tokens")
@Produces("application/xml")
public JAXBElement<GetToken> getokenByName(@QueryParam("name") final String names) {
    if (names != null) {
        Criteria crit = getSession().createCriteria(getPersistentClass());
        Disjunction disjunction = Restrictions.disjunction(); 
        for (String name: names.split(",")) {
            disjunction = disjunction.add(Restrictions.eq("name", name));
        } 
        crit.add(disjunction);
    }
    ...
}

Your idea of splitting the string will work. You can also check how some REST services are done in industry. Check the linkedin people search API

Check the flexibility of the @Path annotation using regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM