This is my Item class
@Entity
@Table(name = "item", schema = "demo_transaction")
@Transactional
public class Item {
@Id
Integer item_id;
String itemName;
Integer price;
@OneToMany(cascade = CascadeType.ALL,fetch= FetchType.EAGER)
List<Event> events;
Event class:
@Entity
@Table(name = "event", schema = "demo_transaction")
@Transactional
public class Event {
@Id
Integer event_id;
String eventName;
As shown Item can have multiple Events. In typical SQL an FK table would be like this:
item_id event_id
1 10
1 20
2 10
2 20
But when I am trying to save these I am getting constrain violation.
Event e1=new Event(10,"FirstEvent");
Event e2=new Event(20,"SecondEvent");
List<Event> lse1=new ArrayList<>();
lse1.add(e1);
lse1.add(e2);
Item item1 = new Item(1,"FirstItem",600,lse1);
List<Event> lse2=new ArrayList<>();
lse1.add(e1);
lse1.add(e2);
Item item2 = new Item(2,"SecondItem",200,lse2);
repo.save(item1);repo.save(item2);
I understand that since eventId is the primary key and I am trying to save twice that's where the constraint getting violated but how would I achieve that FK table? Please help