[英]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
解決此問題的方法是使Offer
的products
屬性成為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.