i'm new in Java Springboot. i want inserting ID from Path Variable ("/id") to my model and save it to database.
i have Request Body
{
"firstName" : "John",
"lastName" : "Doe"
}
i have API for creating record in database like this my UserController
@RestController
@RequestMapping("/api")
public class UserController{
@Autowired
private UserService userService;
@PostMapping("/{id}")
public User create(@RequestBody User user){
return userService.save(user);
}
}
This is my userService
@Service
@Transactional
public class UserService {
@Autowired
private UserRepo userRepo;
//Create
public User save(User user){
return userRepo.save(user);
}
}
this is my userRepo
public interface UserRepo extends CrudRepository<User, Long> {
//CrudRepository will automatically CRUD
}
and the UserModel
@Entity
@Table(name = "users")
public class User implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name", length = 25)
private String firstName;
@Column(name = "last_name", length = 25)
private String lastName;
@Column(name = "full_name", length = 50)
private String fullName;
public User() {
}
public User(Long id, String firstName, String lastName, String fullName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.fullName = fullName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
last, my Problem Response JSON
{
"id": null,
"firstName": "John",
"lastName": "Doe",
"fullName" : null
}
the question is How to inserting id from @PostMapping("/id") to model user.
if the link is http://localhost:8080/api/5 and the response body is
{
"firstName" : "Silvanna",
"lastName" : "Rey"
}
so the response JSON will look like this :
{
"id": 5,
"firstName": "Silvanna",
"lastName": "Rey",
"fullName" : "Silvanna Rey"
}
notes : id not Auto Increment