Bidirectional OneToMany without using mappedBy

2019-08-26 18:44发布

问题:

I have implemented a bidirectional OneToMany association using hibernate annotations. I have seen a lot of examples on the internet and read that the mappedBy attribute needs to be specified on the OneToMany side of the association. (I've been looking at the example here - https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/) However the sample code that I've written without using the mappedBy attribute works perfectly fine. The 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)
@JoinColumn(name="cart_id")
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)
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 code does not use the mappedBy attribute and works fine, data gets saved correctly in the tables. So is my approach correct? In the example at https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/ the mappedBy attribute is used with the OneToMany annotation and JoinColumn is specified with the ManyToOne annotation.

So which approach is correct/better?