Jpa One To Many Relationship Example

By | | Updated : 2021-09-19 | Viewed : 73 times

Jpa One To Many Relationship Example

JPA allows different types of associations. We will see here how to implement it in different approaches.

JPA-OnetoMany-Association-ForeignKey-Annotation

Here we are tiring to save the association @OneToMany author to books. This means one may write many books. First, we will prepare the database tables.

Required tables for @OneToMany
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 @OneToMany association. Here we are using bidirectional association which means one table has references to another one in curd operations. So we can access both tables from any of these two tables using bidirectional.

Book.java
@Entity
@Table(name = "BOOK2")
@Getter
@Setter

public class Book {

	//other properties

	@ManyToOne
	@JoinColumn(name = "AUTHOR_ID", nullable = false)
	private Author author;

}
Author.java
@Entity
@Table(name = "AUTHOR2")
@Getter
@Setter
@AllArgsConstructor
public class Author {

	//other properties

	@OneToMany(mappedBy = "author")
	private Set<Book> books;

}

Notice Author entity contains @OneToMany with mappedBy. mappedBy is used for bidirectional relationships. Bidirectional will be used for traversing in bidirectional ways. The Book entity contains the @ManyToOne annotation with @JoinColumn.

Now it is time to save the entities as given below. Please notice the below given MainClient.

MainClient.java
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.

Tables creation for onetomany association with join table
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.

Author.java
@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;

}
Book.java
@Entity
@Table(name = "BOOK")
@Getter
@Setter

public class Book {

	//remaining properties
}
AuthorBook.java
@Entity
@Table(name = "AUTHOR_BOOK")
@Getter
@Setter
public class AuthorBook {
	
	//remaining properties
}

Now we will save the entities using the below-given code snippet.

MainClient.java
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();
        }
    }
Leave A Reply