Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does hibernate set back reference in @OneToMany @ManyToOne relationship automatically?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading