Spring JPA Hibernate Many to Many – SpringBoot + PostgreSQL

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 :


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

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

spring jpa many to many relationship tables

Create and Drop tables

– Insert:

– Info students & subjects:

IV. Sourcecode


By grokonez | November 6, 2016.

Last updated on February 6, 2020.

Related Posts

11 thoughts on “Spring JPA Hibernate Many to Many – SpringBoot + PostgreSQL”

  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
      2. Spring Form Submission to PostgreSQL – Spring Boot
      3. Spring Web MVC – Spring Form Submission | Spring Boot
      4. How to configure AngularJs with Spring MVC | SpringBoot
      5. How to integrate Http Angularjs with Spring MVC | Spring Boot


  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!

  3. Hi, Admin, thank you for the awesome tutorial?. Just one question, though: How can I explicitly create my own RestController and expose it as a service then consume its methods like listAllStudents etc in an external tool like postman for example? In a many-to-many relationship like this one?

    1. Hi Sydney Molobela,

      You can do it!

      For creating a RestController, you can refer how to expose RestAPIs with SpringBoot via post:
      Spring Framework 4.3 New Feature RequestMapping: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping

      Note: for resolving resolve infinity loop problem, you can use tutorial: Integrate Spring RestAPIs with @JsonView
      More details at:

      How to use @JsonView to serialize/de-serialize and customize JSON format from Java Object.
      How to resolve Json Infinite Recursion problems when working with Jackson


  4. Hi sorry for this question, but how can affect list of subjects to one user: what i mean how to add for one user many subjects and save it in the student_subject?
    Thanks in advance.

Got Something To Say:

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