Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Enter "hello" ( hello )

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the question so it can be answered easily.

Please choose the appropriate section so the question can be searched easily.

Please choose suitable Keywords Ex: question, poll.

Type the description thoroughly and in details.

Choose from here the video type.

Put Video ID here: https://www.youtube.com/watch?v=sdUUx5FdySs Ex: "sdUUx5FdySs".

Enter "hello" ( hello )

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

JPA connections between Entity

JPA is a standard that allows you to map your domain models to the database structure, giving you the flexibility to manipulate objects within our business logic without having to deal with JDBC.

This short guide will serve as a cheat sheet on how you can organize your links in JPA.

Types of Relationships

There are 3 types of relationships between entities:

  • OneToOne – One to One;
  • OneToMany and ManyToOne – one to many and many to one;
  • ManyToMany – many to many.

In order to consider the relationships more comfortably, let’s imagine that we have two entities:

Now, based on these two entities, let’s look at how we can organize the relationships between them.

Before we move on to look at each relationship, let’s prepare our two classes that will represent the Author and Book entity.

Class Author:

package dev.bcode.entity;

@Entity
@Table(name = "authors")
public class Author {
    @Id
    @GeneratedValue
    private Long id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;

    // Getters & Setters
}

Class Book:

package dev.bcode.entity;

@Entity
@Table(name = "books")
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    @Column(name = "name")
    private String name;

    // Getters & Setters
}

OneToOne

In the figure below you can see that there are two entities Author and Book. Since the entities have a OneToOne relationship (1 to 1), you can get the Author of this book from the Book entity, and you can get his book from the Author entity.

Link: OneToOne

This link allows each author in your database to have a link to only one book and a book a link to one author. In other words, one book has one author and vice versa.

Implementing
In order to set up a two-way OneToOne relationship, we need to reference Book in Author class:

@OneToOne(optional = false)
@JoinColumn(name="book_id", unique = true, nullable = false)
private Book book;

// Setters & Getters

In this case the table authors will have a column book_id which will store the id of the book it refers to.

On the Book side we also add a OneToOne relationship:

@OneToOne(optional = false, mappedBy="book")
public Author author;

// Setters & Getters

In this case, there will be no additional columns in the books table, and the relationship will be based on the already defined book field in the Author entity.

Explanation

@OneToOne – indicates the type of relationship, where:

  • optional – defaults to true, indicating whether the link should be mandatory;
  • mappedBy – specifies which field in the Author class the relationship will be based on an existing id in the table.

@JoinColumn – specifies the column to link to our entity, where:

name – the name of this column;

unique – specifies its uniqueness, if true, then the link by id to the same book cannot have another author;

nullable – specifies whether the value in this column can be empty, i.e. null.

OneToMany and ManyToOne

In the figure below we can see the following relationship where OneToMany and ManyToOne are applied together.

This kind of relationship allows us on the Author side of the entity to get a list of books he wrote – this is the OneToMany relationship, and on the Book side we can get from multiple books the same author who wrote the book – this is the ManyToOne relationship.

Communication: OneToMany and ManyToOne

This link can also be arranged in reverse. In this case, the book can have multiple authors, but the Author has only one book – which is most often the exception in the real world.

Implementation
We add the following to the Book essence:

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "author_id", nullable = false)
private Author author;

// Setters & Getters

In this case the table books will have an author_id column containing the author’s id.

On the side of the Author entity we add the following:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "author")
private Set<Book> books;

// Setters & Getters

Now we can get a list of books from a particular author, and we can get the author of a particular book.

Explanation
@ManyToOne – indicates the type of connection many to one. In our case many books to one author.

fetch – by default EAGER specifies that the relationship data should be fetched along with the entity. LAZY will not be fetched when the entity is fetched, and only when the relationship is referenced will an additional query be performed on the database to fetch it.

cascade – is empty by default. Indicates the type of cascade processing, that is, if we specify CascadeType.ALL then when our entity is updated or deleted all records referencing our entity will be deleted or modified and this is more often all bad.

@OneToMany – indicates the type of one-to-many relationship. In our case one author to many books.

mappedBy – specifies which class field the entity’s relationship will be built on.

@JoinColumn – explanation under OneToOne.

ManyToMany
Below is an example of a many-to-many relationship. This type of relationship allows an Author to have multiple books and a book to have multiple authors.

Linking: ManyToMany

For our example of books and authors, this is the best example of communication. After all, there are times when a book is written by multiple authors, and at the same time each of those authors could be writing other books either independently or in collaboration with other authors.

Implementing
We add the following to the essence of Author:

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
    name="authors_books",
    joinColumns = @JoinColumn(name="author_id", referencedColumnName="id"),
    inverseJoinColumns = @JoinColumn(name="book_id", referencedColumnName="id")
)
private Set<Book> books;

// Setters & Getters

And for the essence of Book we add:

@ManyToMany(fetch = FetchType.EAGER, mappedBy = "books")
private Set<Author> users;

// Setters & Getters

If organizing the OneToOne and OneToMany relationship types required an additional column with the id of the entity we want to link to, in the case of ManyToMany a new intermediate table will be created. where each record will contain the id of the author and the id of the book.

Explanation
@ManyToMany – indicates the type of many-to-many relationship, where:

  • fetch – LAZY or EAGER; (detailed explanation in OneToMany and ManyToOne)
  • mappedBy – specifies which field in the class will be used for the link.

@JoinTable – defines how and on the basis of what fields the connection will be created using the intermediate table.

  • name – name of the intermediate table;
  • joinColumns – the field to build a connection for the first entity;
  • inverseJoinColumns – the field for the second entity.

Translation from the source.

Leave a comment

Enter "hello" ( hello )