Reputation: 2743
I have a database and I want to use a endpoint to get the data. But I want to filter the data so that only certain values are returned. What I want is to call the endpoint and then get the data that I wanted out of it. I have made two methods one for calling all the data and another for calling only 1 record in the database. they both working good, but I want to now get multiple records from the database. This is what I have so far:
//This get every record
@RequestMapping(
value = API_PREFIX_1_0 + ENDPOINT_coupon + "/getCoupon",
method = RequestMethod.GET)
public Collection<Coupon> couponGetAll()
{
return couponService.getAll();
}
//this get only one record based on the ID of the table
@RequestMapping(
value = API_PREFIX_1_0 + ENDPOINT_coupon + "/{id}",
method = RequestMethod.GET)
public Coupon couponGetById(@PathVariable(value = "id") final long id) {
return couponService.getById(id);
}
What I want to do is use an array or a list of id to get the data from the server. Thank you for any help with this
Upvotes: 0
Views: 2412
Reputation: 727
The spring CrudRepository already provides a method to find items by a set of ids:
Iterable<T> findAll(Iterable<ID> ids)
this method should be triggered by your service if you are using a CrudRepository in your persistence layer. Then you could add a request parameter to your couponGetAll() method where to get the ids and send it to your service.
@RequestMapping( value = API_PREFIX_1_0 + ENDPOINT_coupon + "/listOfCoupons", method = RequestMethod.GET)
public Iterable<Coupon> couponGetMine(@RequestParam(name="ids")String ids) {
Iterable<Long> longIds = convertToLong(ids);
return couponService.getAll(ids);
}
The client side url to call would look something like this: .../listOfCoupons?ids=2,4,7,3 In the endpoint you extract the numbers out of the string. Maybe there is a nicer solution but this is what is in my mind in this short time.
Convert the id string e.g.:
public Iterable<Long> convertToLong(final String ids){
String[] idArray = ids.split(",");
List<Long> idsAsLong = new ArrayList<>();
for (int i = 0; i < idArray.length; i++) {
idsAsLong.add(Long.parseLong(idArray[i]));
}
return idsAsLong;
}
Upvotes: 4