Home > Software engineering >  Does hibernate set back reference in @OneToMany @ManyToOne relationship automatically?
Does hibernate set back reference in @OneToMany @ManyToOne relationship automatically?

Time:02-14

I have Order entity that has orderItems list.

@OneToMany(mappedBy ="order")
List<OrderItem> orderItems;

OrderItem has back reference to Order

@ManyToOne
Order order;

When I save Order should I manually set backreference in OrderItem entity? Like this

OrderItem orderItem1 = new OrderItem( //constructor );
OrderItem orderItem2 = new OrderItem( //constructor );
List orderItems = Arrays.asList(orderItem1, orderItem2);
Order order = new Order( orderItems);

orderItems.forEach(orderItem -> orderItem.setOrder(order); // like this?

Do Hibernate and Spring data jpa set it automatically?

CodePudding user response:

For creating and updating case , they will not help you to set it automatically and you have to configure the relationship by yourself.

The mappedBy here is to define whether Order.orderItems or OrderItem.order is to used to provide the value for the corresponding DB column that link between them. (i.e. order_id column in order_item table).

If mappedBy is defined , OrderItem.order will be used to provide the value for the relationship. Otherwise , Order.orderItems will be used.

For the loading case , it will help you to set it automatically.

  • Related