Ambiguous handler methods mapped path in spring boot

Sun, Nov 24, 2019

Read in 1 minutes

I had two methods in my controller. Two methods are getEmployeeByID and getEmployeeByFirstName which has the same kind of request mapping path @RequestMapping(path=”/{id}”), @RequestMapping(path=”/{first_name}”)

@RequestMapping(path="/{id}")
	public Optional<Employees> getEmployeeByID(@PathVariable("id")  Long id) {
		return emprepo.findById(id);
	}
@RequestMapping(path="/{first_name}")
public Optional<Employees> getEmployeeByFirstName(@PathVariable("first_name")  String first_name) {
	           return emprepo.findByFirst_Name(first_name);
		}

securitypostmansuccess

When try hit the endpoint http://localhost:8087/employees/Neena I got the below error.

java.lang.IllegalStateException: Ambiguous handler methods mapped for ‘/employees/Steven’: {public java.util.Optional com.theprogrammerguide.springbootproject.dao. HelloController.getEmployeeByID(java.lang.String), public java.util.Optional com.theprogrammerguide.springbootproject.dao. HelloController.getEmployeeByID(java.lang.Long)}

Reason for this error :

Both the mapping @RequestMapping(path=”/{id}”) and @RequestMapping(path=”/{first_name}”) having same endpoint .So ,I changed the @RequestMapping path for firstname like below.

@RequestMapping(path="FirstName/{first_name}")
		public Optional<Employees> getEmployeeByFirstName(@PathVariable("first_name")  String first_name) {
   return emprepo.findByFirst_Name(first_name);
}

So, now when I try to hit the endpoint, http://localhost:8087/employees/FirstName/Neena , I got the output.

{“employee_ID”:101,“first_NAME”:“Neena”, “last_NAME”:“Kochhar”,“email”:“NKOCHHAR”, “phone_NUMBER”:“515.123.4568”, “hire_DATE”:“1987-06-18T05:00:00.000+0000”, “job_ID”:“AD_VP”,“salary”:17000, “commission_PCT”:0, “manager_ID”:100,“department_ID”:90}

Another way to solve the problem :

Instead of @PathVariable , you can use @RequestParam to pass the parameter.

@RequestMapping(method = RequestMethod.GET)
	public List<Employees> getEmployeeBySalary(@RequestParam(value="salary") Long salary ){
		return emprepo.findBySalary(salary);
	}

When I hit with the URL http://localhost:8087/employees/?salary=1700, I got the correct response.

[{“employee_ID”:101, “first_NAME”:“Neena”,“last_NAME”:“Kochhar”, “email”:“NKOCHHAR”, “phone_NUMBER”:“515.123.4568” ,“hire_DATE”:“1987-06-18T05:00:00.000+0000”, “job_ID”:“AD_VP”,“salary”:17000, “commission_PCT”:0, “manager_ID”:100, “department_ID”:90},{“employee_ID”:102, “first_NAME”:“Lex”, “last_NAME”:“De Haan”,“email”:“LDEHAAN”, “phone_NUMBER”:“515.123.4569”,” hire_DATE”:“1987-06-19T05:00:00.000+0000”, “job_ID”:“AD_VP”,“salary”:17000, “commission_PCT”:0, “manager_ID”:100,“department_ID”:90}]