0

私のクラスはこれに似ています:(オファークラス)

@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 に 2 つのオブジェクトを追加しようとしたときです。

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.

2 つの埋め込み可能オブジェクトの 1 つが「金額」フィールドの値が同じであるのに、セットに 2 つの埋め込み可能オブジェクトを永続化できない理由がわかりません。どうにかIDとして扱われるのでしょうか?

このように使用するように設計されていないため、埋め込み可能なオブジェクトのリストを作成しないでください。もしそうなら、製品のエンティティは必要ないが、別のエンティティ (オファー) にセットを保持したい場合はどうすればよいですか?

助けてくれてありがとう

4

1 に答える 1

0

a を使用する場合の問題Setは、コンテンツが一意でなければならないことです。これは a の定義であるためSetです。JPA プロバイダーは、データベース制約を使用してこれを強制しようとします。あなたの例では、Primary KeytheOffer_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

これを修正する方法は、 の代わりにaのproductsプロパティを作成することです:OfferListSet

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
于 2016-05-05T14:45:27.283 に答える