Over a million developers have joined DZone.

Using Annotations for Related JPA Entities

DZone's Guide to

Using Annotations for Related JPA Entities

Want to learn more about how to use annotations? Check out this tutorial on using annotations for related JPA entities.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

The objective of this article is to demonstrate how to reduce the usage of yourEntityManager  while persisting the associated related entities.

While dealing with OData Spring, it provides the AbstractODataProcessor to manage the CRUD operations on entities.

But, in case there is a requirement to have some validations or additional service-to-service calls, we override the relevant methods, via  CreateEntityReadEntity , etc., to handle the same.

When developing business applications, more often than not, you will encounter Parent-Child Entities.

For example, let's take a look at the Order entity and Order Item. Here, the Order Itementity contains the OrderId as a foreign key. And, while adding Order Item, it is required to perform some validations before persisting the same.

Here, I am proposing a simple and appropriate way to manage this using JPA Annotations. 

JPA is a wonderful way to establish foreign key relations between different entity fields.

I will cover the following annotations for the above scenario:

1) @ManyToOne  

2) @OneToMany  

3)  @JoinColumn 

The Order entity should have the following annotations:

public class Order {

    private String OrderId;

    private String BusinessPartner;

    private List<OrderItem> items = new ArrayList<>();  

The OrderItem entity should look like below:

public class OrderItem {

    private String OrderItemId;

    @JoinColumn(name = "\"OrderId\"")
    private Order order;

In the Order entity, @OneToMany is used to enable Items to be stored as an  ArrayList .

In the OrderItem entities, @ManyToOne and @JoinColumn are used to enable fetching or an Order entity.

Now, the CRUD operations on the OrderItementity may not be separately handled using the entity manager. Instead, the OrderItem can be directly added to the Order entity which stores the OrderItem as an ArrayList.

This reduces the effort made by the w.r.t handling of the entity manager and directly looks at the entities that can be used.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

jpa ,java ,annotations ,odata 2 ,order entity ,tutorial ,entities

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}