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