给出一个Product
@Entity
public class Product {
private Long id;
private List<Review> reviews;
public Product() {}
@Id
@GeneratedValue
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@ElementCollection
public List<Review> getReviews() {
return reviews;
}
public void setReviews(List<Review> reviews) {
this.reviews = reviews;
}
// equals() and hashCode() omitted for brevity
}
还有一个可嵌入的Review
@Embeddable
public class Review {
private Customer author;
private String title;
private String comment;
public Review() {}
@ManyToOne(optional = false)
@Column(unique = true)
public Customer getAuthor() {
return author;
}
public void setAuthor(Customer author) {
this.author = author;
}
@Column(nullable = false)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(nullable = false, length = 2000)
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
如何为Review
的作者设置唯一约束。换句话说:我想确定的是,对于给定的产品,每个评论都有不同的作者。
我可以使用@NaturalId
吗?我是否使用@Column(unique = true)
?我已经找到了a similar question on StackOverflow,但就我而言,它是Embeddable的列表,而不仅仅是成员,所以我猜想这种方法行不通。
非常感谢!
答案 0 :(得分:1)
如果您要谈论的是在模式生成期间添加唯一的数据库索引,则可以执行以下操作:
@ElementCollection
@CollectionTable(name = "product_reviews",
uniqueConstraints = {@UnqiqueConstraint(columnNames={"product_id", "author_id"})})
public List<Review> getReviews() {
return reviews;
}