When developing an application, we sometimes reuse the entity classes as command objects. In other words, we use the same entity classes to receive user inputs. See this class for example:

public class Employee {
    private Long id;
    @Size(min=1, max=50)
    private String name;

When you use this class as a command object, the @Size annotation above will ensure that user hasn’t fed a too short or long name.

Now, here comes the glitch: when saving the object, JPA will again run the same validation by default. Not a big deal in rechecking the size, but if you have used custom validation annotations that access the database or do some heavy computing, obviously double checking isn’t worth.

So, the best solution in such case is to switch off validation when saving. To do so, if you are using spring boot, just add one line in your properties file:

spring.jpa.properties.javax.persistence.validation.mode: none

In fact, I’d use this in all my Spring Boot applications.

Happy coding!