我正在编辑作者实体,为作者插入新书和为书籍添加新评论。我在书籍和评论列表中添加了@Size验证。当我合并作者实体时,@ Size验证适用于书籍,但在我的评论列表中出现错误。即使这个列表有价值,对于休眠它也是空的。 This is my code。 为什么@Size不能在第二个级联列表中工作?
public class Author {
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books = new ArrayList<>();
}
public class Book {
@ManyToOne
@JoinColumn(name = "AUTHOR_ID")
private Author author;
@Size(min = 1, message = "At least one review")
@OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Review> reviews = new ArrayList<>();
}
public class Review {
@ManyToOne
@JoinColumn(name = "BOOK_ID")
private Book book;
}
public class AuthorController {
@RequestMapping(method = RequestMethod.PUT)
public void update() {
Author author = new Author();
author.setName("Kathy Sierra");
author = repository.save(author);
Book book = new Book();
book.setAuthor(author);
book.setTitle("Head First Java");
author.getBooks().add(book);
Review review = new Review();
review.setDescription("It's fast, irreverent, fun and engaging!");
review.setBook(book);
book.getReviews().add(review);
repository.save(author);
}
}
显示的错误是:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [com.example.demo.model.Author] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='At least one review', propertyPath=books, rootBeanClass=class com.example.demo.model.Author, messageTemplate='At least one review'}
]] with root cause
javax.validation.ConstraintViolationException: Validation failed for classes [com.example.demo.model.Author] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='At least one review', propertyPath=books, rootBeanClass=class com.example.demo.model.Author, messageTemplate='At least one review'}
]
感谢您的帮助!