使用注释验证值对象

Validating value objects using annotations

我决定在我的实体中使用值对象而不是字符串字段,但我不知道如何(如果可能的话)使用 @Size、@Pattern 等 JPA 注释来验证它们。 这是我的图书实体:

   @Entity
@Access(AccessType.FIELD) // so I can avoid using setters for fields that won't change
public class Book {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long bookId;

  @Embedded
  private Isbn isbn;
  @Embedded
  private Title title;
  @Embedded
  private Author author;
  @Embedded
  private Genre genre;
  @Embedded
  private PublicationYear publicationYear;
  private BigDecimal price;

  // jpa requirement
  public Book() {
  }

  public Book(Isbn isbn, Title title, Author author, Genre genre, PublicationYear publicationYear,
      BigDecimal price) {
    this.isbn = isbn;
    this.title = title;
    this.author = author;
    this.genre = genre;
    this.publicationYear = publicationYear;
    this.price = price;
  }

  public Long getBookId() {
    return bookId;
  }

  public Isbn getIsbn() {
    return isbn;
  }

  public Title getTitle() {
    return title;
  }

  public Author getAuthor() {
    return author;
  }

  public Genre getGenre() {
    return genre;
  }

  public BigDecimal getPrice() {
    return price;
  }

  public PublicationYear getPublicationYear() {
    return publicationYear;
  }

  // setter for price is needed because price of the book can change (discounts and so on)
  public void setPrice(BigDecimal price) {
    this.price = price;
  }

}

这里是我的示例值对象 - 都只是使用字符串。

   public class Isbn {
  private String isbn;

  // jpa requirement
  public Isbn() {
  }

  public Isbn(String isbn) {
    this.isbn = isbn;
  }

  public String getIsbn() {
    return isbn;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    Isbn isbn1 = (Isbn) o;

    return isbn != null ? isbn.equals(isbn1.isbn) : isbn1.isbn == null;
  }

  @Override
  public int hashCode() {
    return isbn != null ? isbn.hashCode() : 0;
  }

  @Override
  public String toString() {
    return "Isbn{" +
        "isbn='" + isbn + '\'' +
        '}';
  }
}

有没有简单的方法来验证这些对象?如果它是我实体中的字符串而不是 Isbn 对象,我可以使用 @Pattern 来匹配正确的 Isbn 并完成它。

EDIT1:也许有比上述方法更好的验证值对象的方法?我对这些东西有点陌生,所以想知道是否有更好的选择来验证我的实体。

您可以使用 @Valid 注释强制验证 Object 字段;

@Entity
@Access(AccessType.FIELD)
public class Book {

  @Embedded @Valid
  private Isbn isbn;
...
}

public class Isbn {
  @Pattern(//Pattern you'd like to enforce)
  private String isbn;
...
}

然后您可以使用以下方法自行验证;

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<User>> violations = validator.validate(book);
//if set is empty, validation is OK