java - Hibernate:Embeddables 列表的唯一约束 (@ElementCollection)
问题描述
给定一个实体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)
吗?我已经在 StackOverflow 上找到了一个类似的问题,但在我的情况下,它是一个 Embeddables 列表,而不仅仅是一个成员,所以我猜这种方法行不通。
提前非常感谢!
解决方案
如果您正在谈论在模式生成期间添加唯一的数据库索引,那么您可以执行以下操作:
@ElementCollection
@CollectionTable(name = "product_reviews",
uniqueConstraints = {@UniqueConstraint(columnNames={"product_id", "author_id"})})
public List<Review> getReviews() {
return reviews;
}
推荐阅读
- angular - Angular Firestore - 如何从 Firestore 获取字段和密钥?
- sql - SQL - 删除重复列错误
- ruby-on-rails - 在 ActiveStorage 中使用变体选项后如何保存图像副本。
- docker - Hyperledger-fabric 区块链多主机
- wpf - 如何修复“InvalidOperationException:必须在 ShaderEffect 上设置 PixelShader”VS2017 错误?
- json - 使用引用验证 Json 架构
- scala - 无法在 playframework 2.6.17 中解析 mock[....]
- android - 将参数传递给 strings.xml ANDROID 中的字体大小
- typescript - 打字稿类创建多次调用
- mysql - 上一年的 SQL 运行总计