@Valid annotation isn't working on my DTO

Viewed 2490

I have this REST API that receives a single Student in order to be saved. The problem that i have in the controller is that i want to receive this json and converted to my StudentDTO but also being validated at the same time using the @Valid annotation but it doesn't work, it just keeps going.

This is my controller:

package com.controllers.usersapi;

import com.dto.usersapi.StudentDTO;
import com.services.usersapi.StudentApiService;
import com.services.usersapi.StudentApiServiceImpl;
import com.utils.OurDataSource;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;


@Path("users")
public class StudentApiRestController {


@POST
@Path("/students")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createNewStudents(@Valid  @RequestBody StudentDTO studentDTO) {
    return OurDataSource.evalEm(entityManager -> {
        Map<String, Object> studentResultsMap;

        StudentApiService studentApiService = new StudentApiServiceImpl(entityManager);

        studentResultsMap = studentApiService.saveStudent(studentDTO);



        return Response.status(Response.Status.CREATED).entity(studentResultsMap).build();
    });
}
 }

This is my DTO

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

public class StudentDTO {

@UniqueEmail
@NotNull
private String emailAddress;
@Min(2)
@NotNull
private String firstName;
@Min(2)
@NotNull
private String lastName;
@Min(2)
@NotNull
private String loginId;
@Min(2)
@NotNull
private String techId;

This is the json that i use

{
"emailAddress": "dvanderlinde@gmaill.com",
"firstName": "Dutch",
"lastName": "Van Der Linde",
"loginId": "dvanderlindeeee",
"id": "DVDL200000"
}

ExceptionMapper

import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;


@Provider
public class DefaultExceptionMapper implements                                            ExceptionMapper<Exception> {


private static final Logger log =            LoggerFactory.getLogger(DefaultExceptionMapper.class);


@Override
public Response toResponse(Exception e) {

    log.error(e.getMessage(), e);

    JsonObject error = new JsonObject();
    error.addProperty("message", e.getMessage());

    return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
            .entity(error)
            .type(MediaType.APPLICATION_JSON)
            .build();
}
}
2 Answers

The bean validation will be enabled automatically if any JSR-303 implementation (such as Hibernate Validator) is available on the classpath. Try adding the following dependency in what is hopefully a spring boot maven based project.

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-validation</artifactId> 
</dependency>

From spring boot version 2.3 and above this dependency needs to specified explicitly. Redeploy and test.

(assuming you are using spring boot) i would refer you the following article.

Check if you have these dependencies inside the pom.xml file of your project, if you haven't try to put them in.

    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>${validation-api}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>${hibernate-validator}</version>
    </dependency>
Related