I'm new at using SpringBoot (this is my first project) and I'm trying to create a simple controller to save users with a post method that requires a JSON RequestBody that also returns a JSON containing the same user as a response. The method seems to work well, I'm gettig a JSON back when I make the post request but for some reason the lastName of the User is always null, as you can see in the image.
(I've used lombok to create getters, setters and constructors)
My User entity is pretty simple:
package com.example.demo.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long userId;
String firstName;
String lastName;
String email;
}
And this is the UserController:
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/")
public User saveUser(@RequestBody User u) {
log.info(u.toString());
return userService.saveUser(u);
}
@GetMapping("/")
public List<User> findAllUsers() {
return userService.findAllUsers();
}
}
I supposed this is a dumb question but haven't found any similar post with a solution.
Thanks a lot!
CodePudding user response:
You have typo in your body
"lastName:":"xxx"
see extra :
as a field name?? So your field is named lastName:
which obviously does not exist in User
thus null.
CodePudding user response:
Request contain a typo error as "lastName:":
? remove the extra colon ":"
used in the "lastName"
.In your postman pass as "lastName":"XXX"
.