Home > Software design >  Bean validation annotation (@Size)not working properly
Bean validation annotation (@Size)not working properly

Time:03-29

import org.javers.core.metamodel.annotation.DiffIgnore;

import javax.persistence.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Size;
import java.util.Set;


@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "project")
public class ProjectComponent extends AbstractEntity {

    @Id
    @Column(name = "id", nullable = false, length = 128)
    private String id;

    @Column(name = "project_name", nullable = false)
    private String projectName;

    @Column(name = "name", nullable = false, columnDefinition = "nvarchar")
    @Size(max = 512, message
            = "Cannot exceed 512 characters")
    private String name;
}

@Size(max=512) I used this in the entity field but whenever I crossed size 512 then this thing should stop on that particular field should not persist into DB and that means should not throw an exception from DB.

CodePudding user response:

As ProjectComponent is an Entity class, I recommend you should use @Length annotation or add length attribute in @Column annotation. I found this article online which explains the difference between these @Size & @Length annotations. Please take a look. Difference between @Size & @Length.

CodePudding user response:

Maybe you should use @Size and @Valid together.

CodePudding user response:

@PrePersist
@PostLoad
void markNotNew() {
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    Set<ConstraintViolation<AbstractEntity>> constraintViolations =
            validator.validate( this );
    constraintViolations.size();
    if(!constraintViolations.isEmpty()) {
        throw new ResourceNotFoundException(constraintViolations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining()));
    }
        this.isNew = false;
}

got the solution thanks friends.

  • Related