I have implemented a bidirectional OneToMany associations using hibernate annotations. Following is my code:
@Entity
@Table(name="Cart")
public class Cart {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="name")
private String name;
@OneToMany(cascade=CascadeType.ALL, mappedBy="cart")
private List<Item> items;
//getters and setters
}
The following is the Item class:
@Entity
@Table(name="Item")
public class Item {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="name")
private String name;
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="cart_id")
private Cart cart;
//getters and setters
}
The following code saves data:
public static void saveCart(Session session) {
Transaction tx = session.beginTransaction();
Cart c1 = new Cart();
c1.setName("Cart 1");
Item item1 = new Item();
item1.setName("item1");
Item item2 = new Item();
item2.setName("item2");
List<Item> items = new ArrayList<Item>();
items.add(item1);
items.add(item2);
c1.setItems(items);
session.save(c1);
tx.commit();
}
This inserts one record in the cart table & 2 records in the items table . However the cart_id column in the item table is not updated. Any idea why?
I have implemented this based on the following example: https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/