High-Performance Java Persistence – Chapter 11 – Relationships
Imagine having a tool that can automatically detect JPA and Hibernate performance issues. Wouldn’t that be just awesome?
Well, Hypersistence Optimizer is that tool! And it works with Spring Boot, Spring Framework, Jakarta EE, Java EE, Quarkus, or Play Framework.
So, enjoy spending your time on the things you love rather than fixing performance issues in your production system on a Saturday night!
Part 2, Chapter 11
Every new chapter of my book is released right after it’s being completed, so the reader doesn’t have to wait for the whole part to be finished to get access to new material.
Table of content
This chapter explains JPA relationships from a data access performance point of view.
11. Relationships 11.1 Relationship types 11.2 @ManyToOne 11.3 @OneToMany 11.3.1 Bidirectional @OneToMany 11.3.2 Unidirectional @OneToMany 11.3.3 Ordered unidirectional @OneToMany 11.3.3.1 @ElementCollection 11.4 @OneToOne 11.4.1 Unidirectional @OneToOne 11.4.2 Bidirectional @OneToOne 11.5 @ManyToMany 11.5.1 Unidirectional @ManyToMany 11.5.2 Bidirectional @ManyToMany 11.5.3 The @OneToMany alternative
Chapter summary
Entity relationships are very common in enterprise applications using JPA as a data persistence technology.
From a database perspective, table relationships can be:
- one-to-many
- one-to-one
- many-to-many
But JPA defines multiple annotations for mapping these table relationships:
@ManyToOne
@OneToMany
@OneToOne
@ManyToMany
@ElementCollection
Unlike the table relationships which have the foreign key on one side only, JPA relationships can be either unidirectional or bidirectional. Unfortunately, not all JPA associations are efficient and this chapter aims to unravel which relationships are useful and which ones you shouldn’t use in a high-performance data access system.
As a rule of thumb, always choose a JPA association that’s based on a child-side @ManyToOne
or @OneToOne
mapping because that’s the most natural way of representing the foreign key side of a table relationship.
You should always remember that JPA relationships are not a mandatory requirement and sometimes a JPQL query is a much more efficient alternative to a collection mapping.
