Search code examples
hibernatehibernate-mapping

Hibernate ManyToMany relationship with independent parent


I have 2 entites

1) Nominee For Nominee management I have separate UI and operation, also this Nominee is used in other modules as well like Loan, etc So It does not have any mapping relation in it.

2) Insurance, which has code like this

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "INSURANCE_NOMINEE", joinColumns = { @JoinColumn(name = "INSURANCE_ID") }, inverseJoinColumns = { @JoinColumn(name = "NOMINEE_ID") })
public Set<Nominee> getNomineeList() {
    return nomineeList;
}

public void setNomineeList(Set<Nominee> nomineeList) {
    this.nomineeList = nomineeList;
}

I have Save Insurance code like this

Insurance insurance = buildInsuranceDomain(insuranceForm);
getHibernateTemplate().merge(insurance);

This works fine, as it inserts record into Insurance and Insurance_Nominee table.

But when I tries to delete this insurance record, it is going to delete record from Nominee table as well, but that should not happen, as that Nominee is used in other module as well like Loan, etc.

Delete code looks like below

getHibernateTemplate().delete(insurance);

So how to specify that relation in Insurance domain entity ?


Solution

  • for Insurance:

    @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
    @JoinTable(name = "INSURANCE_NOMINEE", joinColumns = { @JoinColumn(name = "INSURANCE_ID") }, inverseJoinColumns = { @JoinColumn(name = "NOMINEE_ID") })
    

    and for Nominee:

        @ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
        @JoinTable(name = "INSURANCE_NOMINEE", joinColumns = { @JoinColumn(name = "NOMINEE_ID") }, inverseJoinColumns = { @JoinColumn(name = "INSURANCE_ID") })
    public Set<Insurance> getInsuranceList() {
        return insuranceList;
    }