简体   繁体   中英

How to map multiple many-to-one relations to the same table and same key using Hibernate?

I have two clases like these:

public class Message implements Serializable {
    ...
    private int _messageId;
    private String _message;
    private String type;
    ...

And

public class MyClass implements Serializable {
    private final int myClassId;
    ...
    private final List<Message> messagesOfTypeA;
    private final List<Message> messagesOfTypeB;
    private final List<Message> messagesOfTypeC;
    ...

I want to persist both classes using hibernate. Fields messagesOfTypeA, messagesOfTypeB and messagesOfTypeC group Message objects according to the type field from Message.

How can I map this one-to-many relation between MyClass and Message using XML hibernate mapping? (I'm using Hibernate 3.6)

MyClass

<hibernate-mapping>
  <class name="MyClass" table="my_class">
    <id name="myClassId" column="id">
      <generator class="native"/>
    </id>
    <list name="messagesOfTypeA" cascade="all" fetch="join">
       <key column="myclass_id"/>
       <list-index column="idx"/>
       <one-to-many class ="Message"/>
    </list> 
    <list name="messagesOfTypeB" cascade="all" fetch="join">
       <key column="myclass_id"/>
       <list-index column="idx"/>
       <one-to-many class ="Message"/>
    </list>  
    <list name="messagesOfTypeC" cascade="all" fetch="join">
       <key column="myclass_id"/>
       <list-index column="idx"/>
       <one-to-many class ="Message"/>
    </list>                               
  </class>
</hibernate-mapping>

Message

<hibernate-mapping>
  <class name="Message" table="message">
    <id name="_messageId" column="id">
      <generator class="native"/>
    </id>
    <property name="_message" column="message"/> 
    <property name="type"/>                         
  </class>
</hibernate-mapping>

You end up with a table message with the type discriminant and one FK to the MY_CLASS table.

 CREATE TABLE "MESSAGE" 
   (    "ID" NUMBER(10,0) NOT NULL ENABLE, 
    "MESSAGE" VARCHAR2(255 CHAR), 
    "TYPE" VARCHAR2(255 CHAR), 
    "MYCLASS_ID" NUMBER(10,0), 
    "IDX" NUMBER(10,0), 
     PRIMARY KEY ("ID") 

     CONSTRAINT "FK_MY_CLASS" FOREIGN KEY ("MYCLASS_ID")
       REFERENCES  "MY_CLASS" ("ID") ENABLE
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM