Example
@Data
class MyUser {
@Size(min = 3, max = 15)
private String name;
}
@Data
class MyUser2 {
@Length(min = 3, max = 15)
private String name;
}
@Data
class MyUser3 {
// the resulting column would be generated as a VARCHAR(15) and trying to insert a longer string would result in an SQL error.
// @Column only to specify table column properties as it doesn't provide validations.
// we can use @Column together with @Size to specify database column property with bean validation.
@Column(length = 15)
private String name;
}
MyUserValidationTest.java
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @description
*/
@Slf4j
class MyUserValidationTest {
private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
@Test
public void testSize() {
MyUser myUser = new MyUser();
myUser.setName("mary mary mary mary");
Set<ConstraintViolation<MyUser>> violations = validator.validate(myUser);
assertThat(violations.size()).isEqualTo(1);
assertFalse(violations.isEmpty());
for (ConstraintViolation<?> error : violations) {
log.error(error.getPropertyPath() + ": " + error.getMessage());
}
}
@Test
public void testLength() {
MyUser2 myUser = new MyUser2();
myUser.setName("mary mary mary mary");
Set<ConstraintViolation<MyUser2>> violations = validator.validate(myUser);
assertThat(violations.size()).isEqualTo(1);
assertFalse(violations.isEmpty());
for (ConstraintViolation<?> error : violations) {
log.error(error.getPropertyPath() + ": " + error.getMessage());
}
}
@Test
public void testColumn() {
MyUser3 myUser = new MyUser3();
myUser.setName("mary mary mary mary");
Set<ConstraintViolation<MyUser3>> violations = validator.validate(myUser);
assertTrue(violations.isEmpty());
}
}