使用注释验证值对象

时间:2017-02-27 22:39:11

标签: java hibernate validation jpa value-objects

我决定在我的实体中使用Value Objects而不是String字段,我不知道如何使用JPA Annotations(如@Size,@ Pattern等)来验证它们(如果可能的话)。 这是我的图书实体:

   @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:也许有更好的方法来验证价值对象而不是上面的价值对象?我对这些东西不熟悉,所以想知道是否有更好的选项来验证我的实体。

1 个答案:

答案 0 :(得分:1)

您可以使用@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