Search code examples
javasqlhibernatepersistence

Annotations size smallest than real size in database


Im curious what is implication of defining entity column size smaller tha in database. Is there any danger in that? Without auto generation of scheme. Im using javax.validation.constraints.Size.


Solution

  • The implication is that the validation framework would check if the data fits with the given size. Now assuming that you have inserted data that was bigger than your size value directly in your database, you would have an error when validating an entity from your database as it is too big for your entity field. Please note that I'm refering here to the @Length annotation. This annotation is a Hibernate-specific annotation. @Size is equivalent to @Length, however it is not specific to Hibernate and is defined in the JSR 380 specification.

    In both cases, you should be careful. In order to enforce constraints annotations, you are dependant of a validation implementation such as the Hibernate Validator. Therefore you will need to register a validator and perform the validation over your bean/entity. As a result, the validator will then return constraintViolations on your bean/entity, that you can handle or ignore.

    Now, if we are talking about length of the annotation Column, it is describing physical properties of your database. This definition is not used to enforce validations but rather to generate a database schema based on your entities.

    You can find more details about bean validation in the following Baeldung bean article.

    Moreover, it also have a good article on the difference between @Size/@Length/@Column(length=...)

    In all cases, don't do that... you are actually defining constraints that are not uniform in your application. The validation framework is made to enforce certain properties over your beans. If now you have different properties between your entities and your databases columns, you will add inconsistancy.

    Finally, if no validation is made, obviously no errors will be raised.