繁体   English   中英

Hibernate持久化@Embeddable对象集引发异常

[英]Hibernate persisting Set of @Embeddable objects throws exception

我的课程看起来与此类似:(优惠课程)

@Entity
public class Offer {
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private int id;
    @ElementCollection(fetch = FetchType.LAZY)
    private Set<Product> products;

    ...other fields
}

和产品类别:

@Embeddable
public class Product {
    private String name;
    private String description;
    private int amount;
}

问题是当我尝试保留Offer实体并尝试将两个对象添加到Offer的Set中时:

Product product = new Product("ham", "description1", 1);
Product product = new Product("cheese", "description2", 1);

我收到异常:

Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "offer_products_pkey"
  Details: Key (offer_id, amount)=(1, 1) already exists.

我不知道为什么当其中一个具有相同的“金额”字段值时,为什么不能在集中保留两个可嵌入对象? 是否以某种方式将其视为ID?

也许我不应该创建可嵌入对象的列表,因为它并非旨在像这样使用? 如果是这样,那么,如果我不需要Product的实体,但想将其保留在另一个实体中(优惠)怎么办?

预先感谢您的帮助

使用Set时,问题在于内容必须唯一,因为那是Set的定义。 JPA提供程序将尝试使用数据库约束来强制执行此操作。 在您的示例中,它以Primary Key Offer_id和int Amount的形式添加了约束,尽管恕我直言,它应该为Product属性的所有值添加约束。 看到此问题的最佳方法是启用SQL日志并查看幕后情况:

Hibernate: create table Offer (id integer not null, primary key (id))
Hibernate: create table Offer_products (Offer_id integer not null, amount integer not null, description varchar(255), name varchar(255), primary key (Offer_id, amount))
Hibernate: alter table Offer_products add constraint FKmveai2l6gf4n38tuhcddby3tv foreign key (Offer_id) references Offer

解决此问题的方法是使Offerproducts属性成为List而不是Set

Hibernate: create table Offer (id integer not null, primary key (id))
Hibernate: create table Offer_products (Offer_id integer not null, amount integer not null, description varchar(255), name varchar(255))
Hibernate: alter table Offer_products add constraint FKmveai2l6gf4n38tuhcddby3tv foreign key (Offer_id) references Offer

暂无
暂无

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

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