gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:02:22 25 4
gpt4 key购买 nike

给定一个实体产品

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com