I send JSON file (now from postman) the body is like this:
{
"email": "[email protected]",
"password": "123456"
}
the method on the controller is:
public Company getCompanyDetailsByEmailAndPassword(String email, String password) {
System.out.println("this is email: " email); // added the sysout to understand what arrived.
System.out.println("this is password: " password);
return companyRepository.findByEmailAndPassword(email, password);
}
I get an error -
this is email: {
"email": "[email protected]",
"password": "123456"
}
this is password: null
2022-04-04 18:14:07.830 DEBUG 6076 --- [nio-8080-exec-8] org.hibernate.SQL : select company0_.id as id1_0_, company0_.email as email2_0_, company0_.name as name3_0_, company0_.password as password4_0_ from companies company0_ where company0_.email=? and (company0_.password is null)
Hibernate: select company0_.id as id1_0_, company0_.email as email2_0_, company0_.name as name3_0_, company0_.password as password4_0_ from companies company0_ where company0_.email=? and (company0_.password is null)
2022-04-04 18:14:07.831 TRACE 6076 --- [nio-8080-exec-8] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [{
how to resolve that?
CodePudding user response:
Simplest way is to write a simple class
public class EmailIdHolder {
public String email;
public String password;
// add setters and getters here
}
Change your controller method to:
public Company getCompanyDetailsByEmailAndPassword(EmailIdHolder id) {
System.out.println("this is email: " id.getEmail); // added the sysout to understand what arrived.
System.out.println("this is password: " id.getPassword);
return companyRepository.findByEmailAndPassword(email, password);
}
CodePudding user response:
Since the payload itself is a String (in JSON format), the email parameter is being assigned the entire JSON text.
I'd suggest using a single parameter instead, with a type (maybe named something like "Account") that contains an email field and a password field. Then Spring knows that the two JSON fields belong to a single instance of that class, and you can access the fields of that instance.
https://www.baeldung.com/spring-request-response-body#@requestbody has an example that might be helpful.