1

I im declaring two post methods. One for saving one object and another for saving a list. Now the question is what path should i give to each one in order to not get the typical error :

Caused by: java.lang.IllegalStateException: Ambiguous mapping. Cannot map My controller has the following url, for instance /faults

These are my methods:

 @PostMapping
    public ResponseEntity<FaultDTO> save(@RequestBody FaultDTO faultDTO){...}

 @PostMapping
    public ResponseEntity<List<FaultDTO>> saveAll(@RequestBody ArrayList<FaultDTO> list){...}

What are the correct way of write this api?

  • Not an expert on Spring REST but I assume that the controller is mapping to some URI (like /fault) and you are telling it to handle POST /fault for FaultDTO and List). The answer would be to change the URI of the second method, so that they have distinct (for example, /faults instead of /fault). – NoDataFound Feb 08 '20 at 15:25
  • I thought about that case, then will it not repeat the url? something like that /fault/faults. It is that a good way ? – Bogdan Alin Muresan Feb 08 '20 at 15:31
  • This [post](https://stackoverflow.com/a/3200487/4214241) could be helpful – R.G Feb 08 '20 at 15:52
  • As a simple solution, you can use only the second method and pass only one DTO into the list if it's needed. – adrien olivier Feb 08 '20 at 19:57

3 Answers3

0

You can not have two endpoints bound to the same URI and the same method, because then the application does not know which to use.

You need to do something like this:

@PostMapping
public ResponseEntity<FaultDTO> save(@RequestBody FaultDTO faultDTO){
   /* your code here */
}

@PostMapping("/all")
public ResponseEntity<List<FaultDTO>> saveAll(@RequestBody ArrayList<FaultDTO> list){
    /* your code here */
}
Stefan Repcek
  • 2,553
  • 4
  • 21
  • 29
0

You need to give the two separate methods two separate endpoints in order to segregate them.

    @PostMapping("/save")
    public ResponseEntity<FaultDTO> save(@RequestBody FaultDTO faultDTO){...}

 @PostMapping("/saveAll")
    public ResponseEntity<List<FaultDTO>> saveAll(@RequestBody ArrayList<FaultDTO> list){...}

In your case, the full URL path will be, /faults/save or /faults/saveAll

Tahniat Ashraf
  • 1,020
  • 2
  • 12
  • 21
0

The issue here is that you have would need to give some sort of actual value to post mapping as they are sitting in the same controller, so that the dispatcher servlet knows where to map these requests.

 @PostMapping("/save")
    public ResponseEntity<FaultDTO> save(@RequestBody FaultDTO faultDTO){...}

 @PostMapping("/saveAll")
    public ResponseEntity<List<FaultDTO>> saveAll(@RequestBody ArrayList<FaultDTO> list){...}

Just a follow up to this however! I think you could simply have one save method which takes the ArrayList and then whether the endpoint is passed one Fault or many Faults it shouldn't make much difference as i would assume the saveAll method is doing the same as the save method just many times :)