验证实体而不保存实体

时间:2019-03-20 04:26:52

标签: java hibernate jpa

我有实体

(0.5,0.5,0.1)

如何在不保存的情况下验证@Entity public class MyEntity { @Column(name = "field", nullable = false, length = 10) private String field; } 是否不再是10个字符?

4 个答案:

答案 0 :(得分:1)

使用bean validation

@Entity
public class MyEntity {

    @Size(max = 10)
    @Column(name = "field", nullable = false, length = 10)
    private String field;
}

或者也可以使用休眠特定的注释@Length(max = 10)

然后,您可以使用validator对象验证实体:

public class DemoApplication {

    public static void main(String[] args) {

        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        MyEntity myEntity = new MyEntity();
        Set<ConstraintViolation<MyEntity>> constraintViolations = validator.validate(myEntity));
    }
}

答案 1 :(得分:1)

您的实体类会喜欢下面的东西:

@Entity
public class MyEntity {

    @Size(min = 5, max = 10, message = "field size must be between 5 to 10")
    @Column(name = "field", nullable = false, length = 10)
    private String field;
}

您在这里使用@Column(name = "field", nullable = false, length = 10)。如果字段大小> 10,则它将不会在dabase上保存数据。数据库将给出异常:

在这里您还可以使用@Size(min = 5, max = 10, message = "field size must be between 5 to 10")注释。

这是验证的依赖项

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>

更多注释说明:

  1. @Column是一个JPA批注,模式生成工具使用length属性设置关联的SQL列长度。
  2. @Size是Bean验证批注,用于验证关联的String是否具有长度受最小值和最大值限制的值。
  3. @Length是特定于Hibernate的注释,与@Size的含义相同

希望这会对您有所帮助。

谢谢:)

答案 2 :(得分:0)

@Column具有属性length,可用于设置列的长度,当插入长度更大的值时,这将导致SQL异常。您可以使用@Size(max=SOME_VALUE)进行bean验证。

@Entity
public class MyEntity {

    @Size(max=10)
    @Column(name = "field", nullable = false, length = 10)
    private String field;
}

答案 3 :(得分:0)

我创建了一个小的实用程序类来解决此问题。

public class HibernateValidator {

    private ConcurrentHashMap<Class, List<FieldConstraint>> constraints = new ConcurrentHashMap<>();

    public List<ValidationViolation> validate(Object entity) {
        List<FieldConstraint> constraints = getFieldConstraints(entity);

        return constraints.stream()
                .flatMap(x -> validate(entity, x))
                .collect(Collectors.toList());
    }

    private Stream<ValidationViolation> validate(Object entity, FieldConstraint x) {
        String value;
        try {
            x.getField().setAccessible(true);
            value = (String) x.getField().get(entity);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Can't get value", e);
        }
        if (value != null && value.length() > x.getSize()) {
            return Stream.of(ValidationViolation.builder()
                    .fieldName(x.getField().getName())
                    .build());
        } else {
            return Stream.empty();
        }
    }

    private List<FieldConstraint> getFieldConstraints(Object entity) {
        return constraints.computeIfAbsent(entity.getClass(),
                clazz -> Stream.of(clazz.getDeclaredFields())
                        .filter(x -> x.getType().equals(String.class))
                        .flatMap(x -> {
                            Column annotation = x.getAnnotation(Column.class);
                            if (annotation == null) {
                                return Stream.empty();
                            } else {
                                return Stream.of(FieldConstraint.builder()
                                        .field(x)
                                        .size(annotation.length())
                                        .build());
                            }
                        })
                        .collect(Collectors.toList()));
    }

    @Data
    @Builder
    public static class ValidationViolation {
        private final String fieldName;
    }

    @Data
    @Builder
    private static class FieldConstraint {
        private final Field field;
        private final int size;
    }
}