Search code examples
springhibernatemany-to-manyhibernate-onetomany

Spring Hibernate Relation Mapping


I'm looking for help in one of my project.

I'm having Company Class and Bank Class.

Company Class and Bank Class are to be mapped using Many to Many Relation using Hibernate.

How Do I start? I'm done creating Company Module which is inserting data into table and same for the Bank. But How to show the mapping between both?

Flow Goes like this - Add Company -> Edit/Update -> Add Bank to the previous Company Detail -> Bank Also Add/Update -> View All, which is needed to show The list of Companies and their respective banks.


Solution

  • I assume you use junction table so i would done it like this:

    Company.class

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "nameOfJunctionTable", catalog = "yourDatabaseName", joinColumns = { 
            @JoinColumn(name = "companyId", nullable = false, updatable = false) }, 
            inverseJoinColumns = { @JoinColumn(name = "bankId", 
                    nullable = false, updatable = false) })
    private Collection<Bank> banks;
    

    Bank.class

    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "banks")
    private Collection<Company> companies;