Search code examples
javajsonspringresponse

How to return ID of Db saved JSON in Spring


I am building a sample app for JSON tutorial. After posting JSON object (description and date), an ID should be auto generated in the database. How can I get this ID as the only field in the JSON response?

    @JsonView(View.Summary.class)
    @PostMapping(path = "/api/object/new")
    public Object AddObjectApi(@RequestBody Map<String, String> object) {

        Object newObject = new Object(
            object.get("description"),
            LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS));

        Object savedObject = repository.save(newObject);
        savedCObject.getId();

        return savedObject;
    }

Sample input (Post JSON):

{
   "description" : "This is object description"
}

Sample Output (Returned JSON response):

{
   "id" : "1"
}

Solution

  • You can create a new class which has a field called id

    public class ResponseData{
       public Integer id;
       
       public ResponseData(){
       
       }
    
       public ResponseData(Integer id){
         this.id = id;
       }
    }
    

    Then after saving your object in db you can return the response like this

        @PostMapping(path = "/api/object/new")
        public ResponseData AddObjectApi(@RequestBody Map<String, String> object) {
    
            Object newObject = new Object(
                object.get("description"),
                LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS));
    
            Object savedObject = repository.save(newObject);
            
            ResponseData responseData = new ResponseData(savedObject.getId());
            return responseData;
        }