我决定使用实体中的值对象而不是字符串字段,我不知道使用@Size,例如@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:也许有一种更好的方法来验证价值对象,而不是一个上方的对象?我有点新的东西,所以想知道是否有更好的选择来验证我的实体。
您可以通过利用@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