Search code examples
javaspring-bootjpamany-to-many

Save Many to many relationships between two models in Spring


I have two models which has many to many relationship. And I created repository, service, and controller layers for each one. Now when I make a POST request to each one of them, it is created, but how can we make a connection between them since there is a third table created that contains PKs of each one of the models. The same goes with GET request, it return an empty List.

Can Anyone explain to me how can I POST and GET in two models that have many to many relationships and make link between them.

Thanks


Solution

  • Depending on your implementation of JPA you can achieve the relationship just by annotating the model fields. For example here I use Hibernate and java.persitence annotations to immplement the relationship. I have a class Account which has a list of Subjects. Likewise my Subject has a list of Accounts as a field. To map the relationship I use the java.persitence annotations in this way:

    Class Account.java

    private List<Subject> subjects;
    
    @ManyToMany(cascade = { CascadeType.ALL })
    @JoinTable(
        name = "account_subject", 
        joinColumns = { @JoinColumn(name = "account_id") }, 
        inverseJoinColumns = { @JoinColumn(name = "subject_id") }
    )
    public List<Subject> getSubjects() {
        if(subjects == null) {
            return new LinkedList<Subject>();
        }
        return subjects;
    }
    

    Class Subject.java

    
    private List<Account> accounts;
    
    @ManyToMany(mappedBy = "subjects")
    public List<Account>  getAccounts() {
        return accounts;
    }   
    

    This will automaticlly create a join table called account_subject containing two columns account_id and subject_id, and the line cascade = { CascadeType.ALL } will ensure any operation (update, delete etc..) will be performed on both entities.

    To save an Account entity using Hibernate you simply have to set the required field, for example :

    List<Subject> mySubjects = new List<Subject>();
    mySubjects.add(mySubject);
    myAccount.setSubjects(mySubjects);
    

    and in you repository class we use the Hibernate method saveOrUpdate() to persist

    sessionFactory.getCurrentSession().saveOrUpdate(myAccount);
    
    

    where sessionFactory is your Hibernate SessionFactory object.