High-Performance Java Persistence – Chapter 11 – Relationships
Imagine having a tool that can automatically detect if you are using JPA and Hibernate properly. Hypersistence Optimizer is that tool!
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 126.96.36.199 @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
Entity relationships are very common in enterprise applications using JPA as a data persistence technology.
From a database perspective, table relationships can be:
But JPA defines multiple annotations for mapping these table relationships:
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
@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.