Controller
@RequestMapping(value="/create", method=RequestMethod.POST, consumes={"application/json"})
public Alien addDetails(@RequestBody Alien alien){
return repo.save(alien);
}
Alien.java
@Entity
public class Alien{
@Id
private int id;
private String name;
private String planet;
Getter and setter
Now I want to validate the post json data before saving it to the database. If any of the field is empty then the controller should return an error. For example
{"id": 1, "name": "Alien1", "planet":"Mars" }
This is acceptable json data But if there is any field is missing such as
{"name": "Alien1", "planet":"Mars" }
Then the controller should return an error and not creating the instance of Alien
I tried with @Valid @NotNull still the controller creates an empty instance of Alien and save to the database.
CodePudding user response:
You should add @Validated
annotation to your controller to make @Valid
annotation do the work. You should also annotate fields in your Entity
with constraints.
I.e., name
could be @NotBlank
.
And yes, make sure that you have imported:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
Edit:
In Controller, you should not accept Entity
as a body. Instead, you should create a DTO object and then map it to the Entity
in the service. You should also put validation constraints on the DTO!
CodePudding user response:
First of all, you should add spring boot validation dependency into your pom.xml :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
And then add annotations like @NotBlank or @NotEmpty to verify if a value is assigned to that field or not. Those annotations should be on the top of your entity's attributes which you want to validate them.For example:
public class Alien{
@NotBlank(message="Name is mandatory")
private String name;
}
Finally, add @Valid annotation into your controller method like:
public Alien addDetails(@Valid @RequestBody Alien alien){
return repo.save(alien);
}