1

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

2 Answers 2

1

Hi dear you can get data from path variable using @PathVariable annotation. Once you get id from path variable then you can set it to user model's id property by calling setUserId() method.

Try blow code snippet to get desired output.

@PostMapping("/{id}")
public User create(@PathVariable("id") Long id, @RequestBody User user){
    // Setting data for user id
    user.setId(id);

    // Setting fullName from firstName and lastName
    String fullName = user.getFirstName()+" "+user.getLastName();
    user.setFullName(fullName);
    return userService.save(user);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You sir, this is what i want.
1

The first problem that you mention, which is saving the variable to the database via path param like the example below is works the following way:

http://localhost:8080/api/employees/111

 @RestController
 @RequestMapping("/api")
public class UserController{
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User create(@PathVariable String id){
        return userService.find(user);
    }
}

However as mentioned above these operations are for GET only which means you cant save only an id to the the database you will need to generate automatically an id and save it to the database and POST it to the database with the userbody like you are already doing.

   @Entity
   @Table(name = "users")
   public class User implements Serializable{
   
   // the @GeneratedValue is used to automatically generate the id
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Long id;

 

So in summary the id is used to fetch data from the database via the function find and the save is already generating a userid to save it to the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.