My Parent class
@Entity
public class Trailer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = “trailer_id", nullable = false)
private Long trailerId;
@OneToMany(mappedBy = “trailer”,cascade = CascadeType.ALL,fetch = FetchType.LAZY)
private Set<Item> items;
}
Child class
@Entity
public class Item {
@Id
@Column(name = “upc”, nullable = false)
private Long upc;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "trailer_id", referencedColumnName = "trailer_id")
private Trailer trailer;
}
A Trailer can have multiple unique Items, but the same trailer may bring different set of unique items later.
Service Class
public void addOrderToDB() {
List<Trailer> trailer = new ArrayList<>();
List<Item> items = new ArrayList<>();
trailer = Trailer.builder().build();
Item item1 = Item.builder().setTrailer(trailer).build();
Item item2 = Item.builder().setTrailer(trailer).build();
items.add(item1)
items.add(item2)
ItemRepository.saveAll(items);
}
Why am i trying to saving from many side: because the unique key is upc here.
At the time i am inserting the Item, it is inserting new entry for the Trailer corresponding to each Item entry of the same object.
Expected output:
Trailer table
trailer_id
1
Item table
trailer_id upc
1 001
1 002
Actual output:
Trailer table
trailer_id
1
2
Item table
trailer_id upc
2 001
2 002