How to avoid double validation in Spring Boot applications

Sitewide-10usd300x250 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:

@Entity
public class Employee {

    @Id
    private Long id;

    @Size(min=1, max=50)
    @Column(nullable=false)
    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!

2 thoughts on “How to avoid double validation in Spring Boot applications

  1. Sanjay Post authorReply

    Validations in database can be done through constraints (e.g. not null), triggers etc.

  2. gerry Reply

    Can you also tell configure the validation only to take place at the database layer?
    The reason I ask is you mentioned “if you have used custom validation annotations that access the database”, so I am thinking in a situation like this you want to check when processing is taking place in the database layer and not in service or view layer away from the database ?

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *