I had a little misunderstanding. Let's say I have such an entity:
@Entity
public class Item {
private String description;
}
As well as DTO to this entity:
public class ItemDto {
private String description;
}
As you already understand, all controllers work only with the DTO, that is, I get the DTO from the client part, and then convert it into an entity, and so on.So, I decided to validate the DTO:
public class ItemDto {
@Max(value = 100, message = "Description must not exceed 100 characters")
private String description;
}
Validation works well, but I have a question: do I need to validate entities as well? I always thought that annotations for validation in entity are useless because you still create the necessary tables yourself and set the necessary restrictions. But then the question arises, should entities correspond to the table in the database at all? That is, for example, if I have a NOT NULL
constraint in the table for a field, should I also put the @NotNull
annotation over this field in the entity? The DTO is also not clear. I'm validating the DTO, but this probably doesn't guarantee complete data protection.in other words, in theory, some programmer might decide to do something directly with the entity, but it isn't validated. All this will lead to an error. Or there may be a situation where restrictions are set in the table in the database, but there are no restrictions in the entity.in other words, you can assign any value to the entity, but an error occurs when adding it to the database. Help me deal with the situation. I'm sorry if I didn't explain it very well.
You said
Should entities correspond to the table in the database at all? That is, for example, if I have a
NOT NULL
constraint in the table for a field, should I also put the@NotNull
annotation over this field in the entity?
Bean Validation's purpose is to be used for validating beans. So, for cases where you are not validating the entity, there is clearly no point of placing an unused annotation.
You said
I'm validating the DTO, but this probably doesn't guarantee complete. data protection
JPA
annotations serve this purpose. For example, in the NOT NULL
scenario you mentioned, you can use @Column
as:
@Column(nullable = false)