简体   繁体   中英

Spring Boot: Get required columns from API based on user request

I am trying to implement an API endpoint where a user can request required columns from the API

Basically, this is what I want: This is my products table entity

@Entity
@Table(name ="products") 
class product{
   private Long id;
   private String itemName;
   private String itemDesc;
   private double quantity;
   private double purchaseRate;
   private double saleRate;
   private double onlineSaleRate;
.
.
.
constructor()
getter & setter
}

***And my endpoint is: localhost:8080/api/v1/products

Requirement: I want to write an api endpoint where i request columns based on requirementsa and get those as response

Example: If i only need - itemName, itemPrice and quantity i'll return those as response only. if some user has requirement of itemName, purchaseRate, saleRate, quantity he will get those as a response only.

Right now i am writing new endpoints as per requirements, but i think there is some way to do this.

I want to implement this in my application, i tried google for this but there is no search query that is resulting me as per my requirement.

Create a class with all the fields of your entity with the field types of nullable boxed Boolean (for the purpose of the request json).

class ProductColumns {
    private Boolean itemName;
    private Boolean itemDesc;
    ...

    // setters and getters
}

Then, to construct a custom response, you can use a java Map to acheive this:

public ResponseEntity<Object> getFilteredColumns(ProductColumns columns) {
    Map<String, Object> map = new HashMap<String, Object>();

    if (columns.getItemName() == true) {
        map.put("itemName", [your repo/service method for getting the particular value]);
    }
    if (columns.getItemDesc() == true) {
        map.put("itemDesc", your repo/service method for getting the particular value]);
    }

    ...

    return ResponseEntity<Object>(map, HttpStatus.OK);
}

Of course you should wrap it in some try-catch to your liking.

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