Spring JPA – Many to Many relationship

This tutorial will guide you through the steps configuring Many to Many relationship in database with Spring JPA, Spring Boot & PostgreSql.

Related articles:
How to configure Spring JPA One to One Relationship – SpringBoot
How to configure Spring JPA One to Many Relationship – SpringBoot
Spring Data Rest – How to create a RestAPIs with JPA Many-to-Many relational entities | SpringBoot + MySql + HAL Browser


I. Technology for Many-to-Many relationship tutorial

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– PostgreSQL

II. Overview
1. Many to many database design

student and subject tables have many to many relationship via student_subject table.

many to many relationship database

2. Project structure

Look at Package Explorer to see our project structure:
spring jpa many to many structure of project

3. Step to do

– Create Spring Boot project
– Config Datasource and Hibernate for JPA
– Create models that mapping with Database design.
– Create JPA repositories
– Implement client for use
– Run & Check result

III. Practices
1. Create Spring Boot project

– Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, input project info. Then press Next.
– Press Finish, Spring Boot Project will be created successful.

Add needed dependencies:
– Spring JPA
– Postgresql
– Json

2. Config Datasource and Hibernate for JPA

– Open application.properties, config datasource & hibernate:

3. Create models that mapping with Database design.

– Create Student Entity class:

– Create Subject Entity class:

@Entity: Specifies that the class is an entity. This annotation is applied to the entity class.
@Id: Specifies the primary key of an entity.
@ManyToMany: Defines a many-valued association with many-to-many multiplicity
@JoinTable: Used in the mapping of associations. It is specified on the owning side of an association.
JoinColumn: Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply.

4. Create JPA repositories

– Create StudentRepository & SubjectRepository by extends JpaRepository.

StudentRepository :

SubjectRepository:

JpaRepository: JPA specific extension of {@link org.springframework.data.repository.Repository}

5. Implement client for use

– In main class, implement code for saving and retrieve students & subjects
– Code details:

6. Run & Check result

– Build project with maven: mvn clean install
– Run with command: mvn spring-boot:run

Results:
– 3 tables is created automatically on postgresql DB: student, subject, student_subject

spring jpa many to many relationship tables

Logs:
Create and Drop tables

– Insert:

– Info students & subjects:

IV. Sourcecode

SpringJpaMany2Many


Related Posts



6 thoughts on “Spring JPA – Many to Many relationship”

  1. what if in real input database from multiple jsp input form, rather than directly from queries, are the ORM still work with different way ? need some sample

    1. Hi Jeff,

      For official development & architecture, we need submit the form to webservice. After handling the JSP form by MVC Controller,
      We use the approach in the tutorial for submit data to Database with JPA

      About JPA, it wrap at high level of ORM, so you don’t need to handle or focus on how to ORM framework working.

      How to submit form from JSP file to web controller, you can refer at some ralated posts:

      1. How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot
      http://javasampleapproach.com/java-integration/integrate-jquery-ajax-post-get-spring-boot-web-service
      2. Spring Form Submission to PostgreSQL – Spring Boot
      http://javasampleapproach.com/spring-framework/spring-boot/spring-form-submission-postgresql-spring-boot
      3. Spring Web MVC – Spring Form Submission | Spring Boot
      http://javasampleapproach.com/spring-framework/spring-mvc/spring-web-mvc-form-submission-spring-boot
      4. How to configure AngularJs with Spring MVC | SpringBoot
      http://javasampleapproach.com/spring-framework/spring-boot/configure-angularjs-springboot
      5. How to integrate Http Angularjs with Spring MVC | Spring Boot
      http://javasampleapproach.com/java-integration/http-angularjs-spring-boot

      Regards,

  2. Any idea why this @Transactional annotation is working only on run method?

    If i move the code inside run method into 2 methods, 1 to save data and another to get & print data, and mark those two methods with @Transactional annotation and remove @Transactional from run method, then it gives following error. I had a similar project and there, the save works fine but the print methods fails with lazyInitializationFailed .. no session (i dont want Eager loading)

    java.lang.IllegalStateException: Failed to execute CommandLineRunner

    Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.javasampleapproach.springjpa.many2many.model.Subject; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.javasampleapproach.springjpa.many2many.model.Subject

    Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.javasampleapproach.springjpa.many2many.model.Subject

    1. Hi Nhat,

      If you have id of a student, you can retrieve the student object with statement:

      Then get size from Set of Subjects for that Student:

      Hope it helpful for you!

Got Something To Say:

Your email address will not be published. Required fields are marked *

*