简体   繁体   English

Hibernate:可嵌入列表的唯一约束(@ElementCollection)

[英]Hibernate: Unique constraint for list of Embeddables (@ElementCollection)

Given an Enitiy Product给定一个实体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
}

And an Embeddable Review和可嵌入的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;
    }
}

How can I set an unique constraint for the Review 's author.如何为Review的作者设置唯一约束。 In other words: I want to make sure, that for a given product each review has a different author.换句话说:我想确保对于给定的产品,每条评论都有不同的作者。

Can I use @NaturalId ?我可以使用@NaturalId吗? Do I use @Column(unique = true) ?我使用@Column(unique = true)吗? I already found a similar question on StackOverflow , but in my case it's a list of Embeddables and not just a member, so that that approach won't work, I guess.我已经在 StackOverflow 上发现了一个类似的问题,但在我的情况下,它是一个 Embeddables 列表,而不仅仅是一个成员,所以我猜这种方法是行不通的。

Thanks a lot in advance!非常感谢!

If you are talking about having a unique database index added during schema generation then you can do this as below:如果您正在谈论在模式生成期间添加唯一的数据库索引,那么您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM