views:

1021

answers:

1

Hi there.

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?

Thank you so much and keep in mind: the Hibernate docu is down at the moment. :)

Wolfram

+1  A: 

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 
{
}
ccclark
Ok, I kind of followed your advice, thanks!I am now inserting a ROLE with already existing PERSON and COMPANY. This is ok, as both do and can exist without a ROLE relationship.I configured two @OneToMany mappings in both the PERSON and COMPANY classes plus two @ManyToOne mappings in the ROLE class.I am not too sure about the data integrity so far, but it works as desired. Definitely interesting aspects using inheritance and cascading for these kind of situations. Thanks again!
Wolfram

related questions