简体   繁体   中英

Hibernate persisting Set of @Embeddable objects throws exception

My classes look simiar to this: (Offer class)

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

    ...other fields
}

and Product class:

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

The problem is when I try to persist the Offer entity and try to add two objects to Offer's Set:

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

I receive exception:

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.

I have no idea why can't I persist two embeddable objects in the Set when one of them has the same value of "amount" field? Is it treated as ID somehow?

Maybe I should not create list of embeddable objects as it is not designed to be used like this? If so - then what if I dont need an entity of Product but want to keep set of it in another entity (Offer)?

Thanks in advance for help

The issue when using a Set is that the contents must be unique, since that is the definition of a Set . The JPA provider will try to enforce this with a database constraint. In your example it adds a constraint in the form of a Primary Key the Offer_id and the int Amount , though IMHO it should be adding a constraint for all the values of Product property. The best way to see this is to enable the SQL logs and see what is going on under the covers:

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

The way to fix this is to make the products property of Offer a List instead of the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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