Jpa One To Many Relationship Example
By AmarSivas | | Updated : 2021-09-19 | Viewed : 247 times

JPA allows different types of associations. We will see here how to implement it in different approaches.
Table of Contents:
JPA-OnetoMany-Association-ForeignKey-Annotation
Here we are tiring to save the association
CREATE TABLE `author2` (
`AUTHOR_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`AUTHOR_NAME` VARCHAR(50) NOT NULL,
PRIMARY KEY (`AUTHOR_ID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=15;
CREATE TABLE `book2` (
`BOOK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`AUTHOR_ID` INT(10) UNSIGNED NOT NULL,
`BOOK_NAME` VARCHAR(50) NOT NULL,
`BOOK_PRICE` DOUBLE NOT NULL,
PRIMARY KEY (`BOOK_ID`),
INDEX `AUTHOR_ID` (`AUTHOR_ID`),
CONSTRAINT `BOOKS2_FK` FOREIGN KEY (`AUTHOR_ID`) REFERENCES `author2` (`author_id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=35;
Notice below-given code snippets for
@Entity
@Table(name = "BOOK2")
@Getter
@Setter
public class Book {
//other properties
@ManyToOne
@JoinColumn(name = "AUTHOR_ID", nullable = false)
private Author author;
}
@Entity
@Table(name = "AUTHOR2")
@Getter
@Setter
@AllArgsConstructor
public class Author {
//other properties
@OneToMany(mappedBy = "author")
private Set<Book> books;
}
Notice Author entity contains
Now it is time to save the entities as given below. Please notice the below given MainClient.
public class MainClient {
public static void main(String[] args) {
System.out.println("Main method@MainClient");
try {
EntityManager entityManager = JPAUtils.getEntityManagerFactory().createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
Author author = new Author("Author1");
Book book1 = new Book("Book1", 100.0);
Book book2 = new Book("Book2", 200.0);
Book book3 = new Book("Book3", 300.0);
Set<Book> books = new HashSet<Book>();
books.add(book1);
books.add(book2);
books.add(book3);
author.setBooks(books);
entityManager.persist(author);
book1.setAuthor(author);
book2.setAuthor(author);
book3.setAuthor(author);
entityManager.persist(book1);
entityManager.persist(book1);
entityManager.persist(book1);
transaction.commit();
System.out.println("Session is closed");
} catch (Exception e) {
e.printStackTrace();
}
}
If you want to get the entire repo for JPA-OnetoMany-Association-ForeignKey-Annotation
JPA-OnetoMany-Association-JoinTable-Annotation
We will see first at tables creation and then code for association execution for onetomany.
CREATE TABLE `author` (
`ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(50) NOT NULL,
PRIMARY KEY (`ID`)
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
AUTO_INCREMENT=21;
CREATE TABLE `book` (
`ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`NAME` VARCHAR(50) NOT NULL,
`PRICE` DOUBLE NOT NULL,
PRIMARY KEY (`ID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=79;
CREATE TABLE `author_book` (
`AUTHOR_BOOK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`AUTHOR_ID` INT(10) UNSIGNED NOT NULL,
`BOOK_ID` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`AUTHOR_BOOK_ID`),
INDEX `AUTHOR_ID` (`AUTHOR_ID`),
INDEX `BOOK_ID` (`BOOK_ID`),
CONSTRAINT `AUTHOR_FK` FOREIGN KEY (`AUTHOR_ID`) REFERENCES `author` (`ID`),
CONSTRAINT `BOOK_FK` FOREIGN KEY (`BOOK_ID`) REFERENCES `book` (`ID`)
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB
AUTO_INCREMENT=19;
We will now have a look into the same association with the join table. Please have a look at the below-given code snippets.
@Entity
@Table(name = "AUTHOR")
@Getter
@Setter
@AllArgsConstructor
public class Author {
//remaining properties
@OneToMany(cascade= CascadeType.ALL)
@JoinTable(name="AUTHOR_BOOK", joinColumns={@JoinColumn(name="AUTHOR_ID", referencedColumnName="ID")}
, inverseJoinColumns={@JoinColumn(name="BOOK_ID", referencedColumnName="ID")})
private Set<Book> books;
}
@Entity
@Table(name = "BOOK")
@Getter
@Setter
public class Book {
//remaining properties
}
@Entity
@Table(name = "AUTHOR_BOOK")
@Getter
@Setter
public class AuthorBook {
//remaining properties
}
Now we will save the entities using the below-given code snippet.
public class MainClient {
public static void main(String[] args) {
System.out.println("Main method@MainClient");
try {
EntityManager entityManager = JPAUtils.getEntityManagerFactory().createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
Author author = new Author("Author1");
Book book1 = new Book("Book1", 100.0);
Book book2 = new Book("Book2", 200.0);
Book book3 = new Book("Book3", 300.0);
Set<Book> books = new HashSet<Book>();
books.add(book1);
books.add(book2);
books.add(book3);
author.setBooks(books);
entityManager.persist(author);
transaction.commit();
System.out.println("Session is closed");
} catch (Exception e) {
e.printStackTrace();
}
}
To get GitHub JPA-OnetoMany-Association-JoinTable-Annotation-Example-App repo.