简体   繁体   English

休眠:如何在xml中创建复合外键?

[英]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). 我有一个包含复合主键(开始日期和结束日期)的类Event

A EventPlanning class holds a Set of such Event objects and has to persist them using hibernate with XML. 一个EventPlanning类包含一个Set这样的Event对象,并有他们使用带有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 column="event_id">无效:

<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: 事件xml如下所示:

<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. 在与JPA和Hibernate一起工作了更长的时间之后,我只是说您根本不应该使用复合主键。 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. 缓存使用id作为指向缓存值的键,数据检索方法(例如getload将id用作参数等。通过使id字段获得的好处可以抵消其所需的额外空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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