I am trying to make a springboot project, but I came across a problem I do not understand. I am using the H2 database, for storing some data, when i do the post request with postman the data being sent to the database has null values, so I am saving a user with name and email. both name and email are null.
This is my entity class, I have 2 constructors, since it does not let me not have the default one, but it seems that it just jumps to the default even when i give a json body?
@Entity
@Table(name = "users") // Specify the table name
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
public User(String username, String email) {
this.username = username;
this.email = email;
}
public User() {
}
The controller
@RestController
@RequestMapping("/api/users")
public class UserController {
....
@PostMapping
public User createUser(@RequestBody User user) {
System.out.println("Received Request Body: " + user.getUsername());
return userService.createUser(user);
}
code from the service
public User createUser(User user) {
return userRepository.save(user);
}
the repo just extends extends JpaRepository<User, Long> { }
The result from H2 when i send this post
{
"username": "john_doe",
"email": "[email protected]" }
You have to add getters and setters to your entity class like:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
public User(String username, String email) {
this.username = username;
this.email = email;
}
public User() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Or just use lombok
to avoid all of this code. You can learn about it HERE.