Postman return null values in response - spring-boot

I have created a simple Java spring boot API to add employees. I want to check to employee add endpoint. When I try with it in postman I am getting null values in response.
But its status is 200 and id auto-increment is also working fine.
Controller:
#RestController
#RequestMapping("/api/vi")
public class EmplyeeController {
#PostMapping("/add")
public Employee addEmployee(#RequestBody Employee employee) {
return employeeRepository.save(employee);
}
}
Repository:
#Repository
public interface EmployeeRepository extends JpaRepository<Employee,
Long>{}
How can I solve this? This is my first spring boot application. I wish your help to solve this. Thank you.

You need to correct your payload as Spring bind your payload with Entity when it should have the same attribute but In your case you are using _ "underscore" in your payload and in Entity you are using camelCase so the solution would be updating the post payload and then it will work.
{
"emailAddress":"",
"firstName":"",
"lastName":""
}

Hello i was also facing the same issue, check in application.properties where spring.datasource.url=jdbc:mysql://127.0.0.1:3306/product, weather its mapped to exact schema name in mysql db, i.e case sensitive, previously i have given as /Product

I was having the same problem solved by adding #RequestBody
public ResponseEntity<Employee> addEmployee(#RequestBody Employee employee){
Employee employee1 = employeeService.addEmployee(employee);
return new ResponseEntity<>(employee1,HttpStatus.CREATED);
}

Basically we want to provide the fields as same as entity and check once if there is spaces in the postman like
Ex: " empname":"sudha" (wrong) -> if u will give like this in that time also will get nulls
"empname":"sudha" (right)

Related

Returning only the first 10 record - Redis OM

I’m using Redis OM for spring boot, I am having trouble querying objects because it only returns the first 10 records.
Repository Class:
public interface RedisBillerRepository extends RedisDocumentRepository<Biller, Long> {
List<Biller> findByClientIds(String clientId);
}
Is there a way to return ALL the objects with the specific clientId? Not the first 10 only.
The only way which i found was with the interface Page. For example your Repository would look like this:
public interface RedisBillerRepository extends RedisDocumentRepository<Biller, Long> {
Page<Biller> findByClientIds(String clientId, Pageable pageable);
}
And your class could look like this
public class BillerService {
#Autowired
RedisBillerRepository redisBillerRepository;
public List<Biller> getAllClientsById(String clientId){
Pageable pageRequest = PageRequest.of(0, 500000);
Page<Biller> foundBillers = redisBillerRepository.findByClientIds(clientId, pageRequest);
List<Biller> billersAsList = foundBillers.getContent();
return billersAsList;
}
}
You have to set the limit for now.
I'm the author of the library... #member2 is correct. RediSearch currently has a default for the underlying FT.SEARCH (https://redis.io/commands/ft.search/) method of returning the first 10 records found. To override that, the only way to do so currently is to use the Pagination constructs in Spring.
I will expose a configuration parameter in upcoming versions to set the MAX globally.

Spring Data JPA returning wrong results

I am testing Spring-Data-JPA with Spring-Boot, using hibernate-core 5.4.2.Final version.
For example, I have a Users table containing address and other columns.
My repository interface for this table is as below.
public interface UsersRepository extends JpaRepository<Users, Integer> {
List<Users> findByAddressContaining(String keyword)
}
To my knowledge, if I name the method like I did, the query below will be executed.
SELECT * FROM Users u WHERE address LIKE '%keyword%';
The problem is, this partly works.
For example, there are two datas in users table, each datas having address of "abc" and "cde".
If i test the findByAddressContaing("abc"), the result size of List<> is 2.
Right after if I run findByAddressContaining("de"), the result should be 1, but it is 2.
If i run the same method findByAddressContaining("de") again, then the result becomes 1.
I can't find the way to solve this problem. Any suggestions would be helpful. :)
THE PROBLEM WAS NOT WITH THE Spring-Data-JPA, it was with Request Parameter.
This is my controller method.
#GetMapping("/v2/warehouses")
public void getAllWarehouses(#RequestParam(name = "address") String address,
#RequestParam(name = "limit") Integer limit,
#RequestParam(name = "offset") Integer offset,
HttpServletResponse response) {
System.err.println("Request Param Address : " + address");
If I send request to the correct path using Postman, sometimes address comes as blank.("")
Does this happen normally??
So the basic problem was not with the #RequestParam annotation, it was with the application.properties file.
After I added server.tomcat.uri-encoding=UTF-8 to the properties file, the bug didn't happen anymore.
Thanks!

Spring RestController - findById and findByEmail request method not working (Ambiguous handler)

I want to retrieve user's info either based on the ID or the Email. Below is the controller class I wrote:
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserDao userDao;
#GetMapping(value = "/{id:\\d+}")
public User findOneById(#PathVariable("id") final Integer userId) {
return userDao.findById(userId).get();
}
#GetMapping(value = "/{email}")
public User findOneByEmail(#PathVariable("email") final String email) {
return userDao.findByEmail(email).get();
}
The code is not working and giving error
java.lang.IllegalStateException: Ambiguous handler methods mapped for HTTP path 'http://localhost:8080/users/12223': {public com.example.persistence.model.User com.example.rest.controller.UserController.findOneById(java.lang.Integer), public com.example.persistence.model.User com.example.rest.controller.UserController.findOneByEmail(java.lang.String)}.
I thought Regex would solve this issue but unfortunately it didn't.
The reason for error I understood, but what is the way to handle such requirement?
Your problem is that http://localhost:8080/users/12223 matches both /users/{id:\\d+} and /users/{email}. 12223 is a valid parameter for both methods:
12223 matches {id:\\d+} because it has all digits
12223 matches {email} because regex expression is not specified and any parameter will match email.
Spring can't select an appropriate endpoint and gives an error: Ambiguous handler methods mapped for HTTP path.
If you try another parameter, say: http://localhost:8080/users/somebody#example.com, there will be no error. Spring will be able to find out, that somebody#example.com doesn't match id and matches email.
As JB Nizet mentioned in the comments, you have 2 ways to solve this:
Specify regex for the e-mail to match e-mail format, something like {email:.+#.+\..+}
Clarify endpoints like pDer666 recommended:
#GetMapping(value = "/email/{email}")
#GetMapping(value = "/id/{id:\d+}")
There are different ways to solve this. It is possible to provide two GetMappings with different paths or you use query parameters in only one get request. If the Email is Set you retrieve data by Email If the other is Set retrieve it by the other parameter. With this solution you can easily add more parameters to search by and you have the posibility to query your data by OR or AND without adding a new controller method.
Url : http://localhost:8080/users?email=asdf#somewhere.com OR http://localhost:8080/users?id=1234
#GetMapping
#ResponseBody
public String findOne(#RequestParam("id") long id, #RequestParam("email") String email) {
...
}

Spring Boot Delete controller returns 204 , but does not delete data from the database

Following is my code to delete an existing row from the checklist table.
On sending request spring returns 204.
But the data does not get deleted from the database.
On doing a get request I still get the data that I wanted to be deleted.
Any help will be appreciated. Thank you
#RequestMapping(value = "/{id}", method = RequestMethod.DELETE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.NO_CONTENT)
#Transactional(Transactional.TxType.REQUIRES_NEW)
public void deleteChecklist(#PathVariable("id") Long checklistId) throws ChecklistResourceNotFoundException {
Checklist checklist = RestPreconditions.checkFound(checklistRepository.findOne(checklistId));
checklistRepository.delete(checklist);
}
#Repository
public interface ChecklistRepository extends CrudRepository<Checklist, Long> {
}
You're setting #ResponseStatus(HttpStatus.NO_CONTENT). No wonder Spring returns 204. But ideally it should have deleted the entry. Just verify the call to get data from repo actually returns the Checklist entity. If it does, then the delete should be working provided you have DB level privilege to do so.

#PathVariable Spring Controller

I'm working on a spring web application using thymeleaf as a view resolver lately, and when developping my controllers, i faced a new situation :
i'm not really sure about it but can the #Pathvariable passed from the view be an object ? (a compound key of a model to be precise ? )
i used ids before, but most of them were simple int ids, i just want to know if passing an object (which is the primary key of my object) is possible , and not simple int ids ?
And Thank you
You can use Spring PropertyEditor or Spring Converter see Spring Convertor
example
public class CategoryConverter implements Converter<String, Category>{
#Autowired
private CategoryService categoryService;
public Category convert(String id) {
return categoryService.findById(Long.valueOf(id));
}
}
But you may meet some problem when saving object directly to database.

Resources