简体   繁体   中英

hibernate: how to create a composite foreign key in xml?

I have a class Event containing a composite primary key (start date and end date).

A EventPlanning class holds a Set of such Event objects and has to persist them using hibernate with XML. I can do this for classes with a common primary key:

<!-- EventPlanning xml -->
....
<id name="id" column="id">
<generator class="native" />
</id>
<property name="name" column="name" type="string" update="false" />

<set name="events" table="events" cascade="all">
    <key column="event_id">   // ###### here! ######
    </key>
    <one-to-many class="myPackage.Event" />
</set>
...

but I can't find out how this works with a composite key..

replacing the <key column="event_id"> with the following code doesn't work:

<key>
    <property column="start_date" />
    <property column="end_date" />
</key>

I'd be glad if somebody can show me the right syntax! :)

the Event xml looks like this:

<class name="myPackage.Even" table="events">

        <composite-id>
            <key-property name="startDate" column="start_date" type="date" />
            <key-property name="endDate" column="end_date" type="date" />
        </composite-id>

        <property name="signinDeadline" column="signin_deadline"
            type="date" />
        <property name="confirmationDeadline" column="confirmation_deadline"
            type="date" />

        <set name="participants" table="participants" cascade="all">
            <key column="event_id">
            </key>
            <one-to-many class="myPackage.Participants" />
        </set>

    </class>

thanks in advance! :)

Something like this works for me:

<class name="YourClass" table="your_table" ...>
  <composite-id name="compositeId" class="DoubleDate">
     <key-property name="start_date" column="start_date"/>
     <key-property name="end_date" column="end_date"/>
  </composite-id>
  ...
 </class>

public class DoubleDate implements Serializable {
   private Date start_date, end_date;
   public DoubleDate() {
   }
   // setters, getters
}

public class YourClass {
   private DoubleDate compositeId;
   // public no args ctr, getters, setters, etc
}

After having now worked longer with JPA and Hibernate, I'd just say that you simply should not use composite primary keys. Caches use ids as keys that point to cached values, data retrieving methods like get and load expect the id as parameter etc. The advantages gained by having an id field pay off against the additional space it needs.

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