8

Just encountered a bug, where the issue was that i had:

@Column(name = "ACTIVE")
@NotNull
private boolean active;

In my code I had forgot to set the value but it still "worked" as the default of boolean is false. I have now changed it to Boolean so that it fails the validation if it is not actively set.

Why am I allowed to have @NotNull constraints to things that can obviously not be null? Is it refactoring reasons, so if i change to Boolean as i have done now, i still keep the intended constraint?

Are there any good ideas catch these issues (except more tests for just this purpose)? Or should i keep away from using primitives?

Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75
  • 2
    Because creating the database from the schema declared by annotations need to know the column will be not null. Later, you may decide to switch from `boolean` to any type the boolean can convert into and is nullable (not only Boolean but also an integral, like Short/Integer/etc). For ex, mysql allocate and entire `tinyint` (`int8_t`) for a bool. – Adrian Colomitchi Oct 21 '16 at 09:15
  • 3
    The JavaDoc of `javax.validation.constraints.NotNull` explicitly states, that it accepts any type and it wouldn't make much sense to not do that. The sole purpose of this annotation is to check if the annotated variable is not null. Checking if the type allows `null` or not would already fail the Single responsibility principle. – Tom Oct 21 '16 at 09:15
  • @AdrianColomitchi, thanks I think that is a very valid point. I personally don't use that functionallity but i can see why it is important. – Viktor Mellgren Oct 21 '16 at 10:13

1 Answers1

4

As javadoc says The annotated element must not be null. Accepts any type.

It can be any type it just checks whether the variable is not null or not, it has nothing to do with whether it accepts null or not.

As mentioned it is applicable for METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER.

@Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
Prasanna Kumar H A
  • 3,341
  • 6
  • 24
  • 52
  • I understand that it does, my question was more *why* it was allowed for primitives. – Viktor Mellgren Oct 21 '16 at 10:14
  • I don't know the particular reason as i coudn't able to find the official documentation but go through [this](http://stackoverflow.com/questions/1458535/which-types-can-be-used-for-java-annotation-members)(not entirely related though) – Prasanna Kumar H A Oct 21 '16 at 10:19