【问题标题】:Hibernate - mapping a class more than onceHibernate - 不止一次映射一个类
【发布时间】:2013-01-17 17:16:23
【问题描述】:

我正在尝试添加一个持久化新添加的类。当我开始时,有一个名为 Tournament 的类,它有一个 Schedule 类型的成员,它简单地包装了一个 Session 对象列表。这是该类的休眠映射。它的id和其他字段都被省略了。

<hibernate-mapping default-access="field">
  <class name="fully.qualified.class.Tournament" table="tournaments">
    <component name="schedule" class="fully.qualified.class.Schedule">
      <list name="sessions" cascade="all-delete-orphan" lazy="true" table="tournament_sessions" >
        <key column="tournament_id" not-null="true"/>
        <index column="session_index"/>
        <one-to-many class="fully.qualified.class.Session"/>
      </list>
    </component>
  </class>
</hibernate-mapping>

现在我需要创建一个新类OtherThing,它也有一个Schedule. 所以我复制了会话表并将其命名为other_thing_sessions. 我还创建了一个看起来与上面非常相似的休眠映射:

<hibernate-mapping default-access="field">
  <class name="fully.qualified.class.OtherThing" table="other_things">
    <component name="schedule" class="fully.qualified.class.Schedule">
      <list name="sessions" cascade="all-delete-orphan" lazy="true" table="other_thing_sessions" >
        <key column="other_thing_id" not-null="true"/>
        <index column="session_index"/>
        <one-to-many class="fully.qualified.class.Session"/>
      </list>
    </component>
  </class>
</hibernate-mapping>

令我惊讶的是,这导致了以下错误:

org.hibernate.MappingException: Repeated column in mapping for entity: fully.qualified.class.Session column: session_index (should be mapped with insert="false" update="false")

似乎hibernate不喜欢我反复使用这个类,所以我尝试将属性entity-name="OtherThingSession"添加到一对多元素。现在我遇到了这个错误:

org.hibernate.MappingException: Association references unmapped class: OtherThingSession

这让我愣了一分钟,所以我回去查看我原来的错误。我决定只更改新映射中索引列的名称。这没有得到hibernate的抱怨,但是坚持没有用。当我试图坚持OtherThing.时,它似乎尝试将会话对象插入tournament_sessions表中

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    你不能两次映射一个类。 Hibernate 无法处理这个问题。如您所见,您会遇到奇怪的错误。 (当一个类被映射两次时,一级缓存也不能正常工作,因为 Hibernate 使用该类来决定一个缓存实例属于哪个表。我的效果是在 uniqueResult( ) 认为表中只有一个。)

    你可以做什么:

    例如,创建两个“空”类,它们扩展 Session 而不向其添加任何功能

    public class TournamentSession extends Session {}
    
    public class OtherSession extends Session {}
    

    然后在一个&lt;one-to-many&gt; 属性中使用TournamentSession,在另一个属性中使用OtherSessionSession 本身绝不能被映射,也不能在 Hibernate 属性中使用。

    【讨论】:

      猜你喜欢
      • 2015-04-03
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 2012-04-21
      相关资源
      最近更新 更多