首页 > 解决方案 > 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 列表,而不仅仅是一个成员,所以我猜这种方法行不通。

提前非常感谢!

标签: javahibernatejpa

解决方案


如果您正在谈论在模式生成期间添加唯一的数据库索引,那么您可以执行以下操作:

@ElementCollection
@CollectionTable(name = "product_reviews", 
       uniqueConstraints = {@UniqueConstraint(columnNames={"product_id", "author_id"})})
public List<Review> getReviews() {
    return reviews;
}

推荐阅读