Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

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:

@Entity
public class Order {

    @Id
    @Column
    private String OrderId;

    @Column
    private String BusinessPartner;

    @OneToMany(mappedBy="order")
    private List<OrderItem> items = new ArrayList<>();  
}


The OrderItem entity should look like below:

@Entity
public class OrderItem {

    @Id
    @Column
    private String OrderItemId;

    @ManyToOne
    @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.

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
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 }}