Wolfram
Wolfram

Reputation: 8052

Hibernate - @ManyToMany with additional fields in mapping entity

My simplified Entity Scenario is as follows:

A PERSON is associated to a COMPANY in a specific ROLE (yawn).

My first thought was to configure a ManyToMany relationship between PERSON and COMPANY. However and apparently, I can not include the type of ROLE in the ROLE table that way (as another field the two foreign keys).

I acknowledge that the right way to do this is to use two OneToMany relationship and include the ROLE as an entity on its own (answered already on stackoverflow).

But this is where I am stuck: I use an html form to add a person to a company and select the adequate role, how do I save this to the database or better: how do I tell Hibernate to save it. A Person has a List and so does the Company. A Role has a Person and a Company. How do they meet in the middle? So basically what I am asking:

How is the exact Hibernate mapping configuration so that I can save a Person with a Role in a Company in one step?

Upvotes: 2

Views: 2331

Answers (1)

ccclark
ccclark

Reputation: 209

Look at Cascading and Table inheritance. For example the code below would represent three tables. A Company Table, a Role table with a CATG and a User table. The role table would use single table inheritance where the CATG would be managed by hibernate and hibernate would create the right class based on the CATG column value and the mapping. And cascading would insert the role at the same time as the user.

@Table( name = "USER" )
Public User
{


    @ManyToOne( fetch = FetchType.LAZY )
    @JoinColumn(  cascade = CascadeType.ALL, name="ROLE_NAME" )
    private CompanyRole   role;

}

@Inheritance( strategy = InheritanceType.SINGLE_TABLE )
@DiscriminatorColumn( name="CATG", discriminatorType=DiscriminatorType.STRING )
@Table( name = "Role" )
public Role
{

}

@DiscriminatorValue( "CMPY_ROLE" )
public CompanyRole extends Role
{

    private Company company
}

@Table( name = "COMPANY" )
Public Company 
{
}

Upvotes: 2

Related Questions