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

标签 java hibernate jpa

给定一个实体产品

@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
}

以及可嵌入的评论

@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;
    }
}

如何为评论的作者设置唯一约束。换句话说:我想确保对于给定的产品,每条评论都有不同的作者。

我可以使用@NaturalId吗?我是否使用@Column(unique = true)?我已经找到a similar question on StackOverflow ,但就我而言,它是一个可嵌入列表,而不仅仅是一个成员,因此我猜这种方法行不通。

提前非常感谢!

最佳答案

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

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

关于java - Hibernate:可嵌入列表的唯一约束(@ElementCollection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51227982/

相关文章:

java - Spring bean销毁方法

postgresql - 直接 hibernate native 查询工作正常,但使用 setParameter 查询未更新 postgresql 数据库

jakarta-ee - JPA 不能用于在 HttpSession 中管理的 CDI 范围?

java - DuplicateMappingException 表 [] 包含由多个逻辑列名称引用的物理列名称 [] : [_id], [Id]

java - @Transactional注解是否避免并发访问业务层方法

java - 我遇到了麻烦。我不断收到运行时错误,因为它同时打印 2 行?

java - 如何同时加载和查询 RDF

java - 映射实体,列表作为映射值。通过 JDBC 语句执行 DDL "drop table if exists ` single_line`"时出错

Hibernate 实体作为静态类

oracle - 无法使用 Oracle 序列获取 EclipseLink DynamicEntity 的工作