Search code examples
javahibernateormentity-relationshipforeign-key-relationship

Hibernate: many-to-many through additional table


I have these tables, organization can be a sender or receiver of many messages, a msg can have 2 organizations that send it or receive. I know that my db doesnt make sense but i cant change it:

enter imad description here

So, do i connect SenderReceiver to Msg as 1-to-n, and Organization to SenderReceiver as n-to-1? or vice versa n-to1 and 1-to-n?

Senderreceiver:

public class Senderreceiver implements java.io.Serializable {

        private Set<Organization> organizations = new HashSet();
        private Set<Msg> msg = new HashSet();

xml file:

<set fetch="select" inverse="true" lazy="true" name="msgs" table="MSG">
      <key>
        <column name="MsgID" not-null="true"/>
      </key>
      <one-to-many class="entity3.Msg"/>
    </set>



<set fetch="select" inverse="true" lazy="true" name="organizations"  table="ORGANIZATION">
      <key>
        <column name="OrganizationID" not-null="true"/>
      </key>
      <one-to-many class="entity3.Organization"/>
    </set>

Msg:

public class Msg implements java.io.Serializable {

        private Senderreceiver senderreceiver;

xml:

<many-to-one class="entity3.Senderreceiver" fetch="select" name="senderreceiver">
      <column name="SenderReceiverID" not-null="true"/>
    </many-to-one>

Organization:

public class Organization implements java.io.Serializable {

        private Senderreceiver senderreceiver;

xml:

 <many-to-one class="entity3.Senderreceiver" fetch="select" name="senderreceiver">
          <column name="SenderReceiverID" not-null="true"/>
        </many-to-one>

Any help would be appreceited. Thanks in advance!


Solution

  • I would suggest this:

    As I see it, this is 2-N relation. An organization can send many messages and a message can be sent or received only by one or two organization. You dont need a connection table.

    put a set of messages in the organization - this will represent the messages sent/received by the organization. You can also make 2 sets - sentMSGS and receivedMSGS.

    and put a FK of the organization in the message itself, as this will represnt the oganization of the message. You can put a sentID and receviedID in a message.

    I think this will make the understanding of the table and the program more easy.

    If you choose to stay with the original relations, a many to many relation will be presented as:

    1-N-1 (Organization-SenderReceiver-Msg).

    Organization-SenderReceiver is 1-N and SenderReceiver-Msg is N-1.

    So you put a collection of SenderReceiver in both the Organization and the Msg classes. And objects of both Organization and Msg inside the SenderReceiver.