1

我有一个非常具体的场景如下。

public class Person
{
    Long id;
    Collection<PersonRelation> personRelationCollection = new LinkedHashSet<PersonRelation>();
/**
  has respective getter and setter
**/
}

public class PersonRelation
{
    Long id;
    Long parentPersonId;  // here I don't want parentPersonId of type Person
    Long childPersonId;   // here also I don't want childPersonId of type Person
    String relationType;
/**
  has respective getter setter
**/
}

在我的映射文件中,我有以下

<class name="Person" table="PERSON">
     <id name="id" column="IDENTIFIER">
        <generator class="native"/>
    </id>
    <set 
        name="personRelationCollection"
        table="PERSON_RELATION"
        cascade="all"
       >
       <key column="PARENT_PERSON_ID"/>
       <one-to-many class="PersonRelation"/>
    </set>
</class>

<class name="PersonRelation" table="PERSON_RELATION">
    <id name="id" column="IDENTIFIER">
        <generator class="native"/>
    </id>

   <!-- following many-to-one mapping doesn't work-->
   <!-- I need help here to satisfy my requirement -->
    <many-to-one 
          name="parentPersonId" 
          column="PARENT_PERSON_ID"
          class="Person"
          not-null="true"/>   
    <Property name="childPersonId" column="CHILD_PERSON_ID"/>
    <property name="relationType" column="RELATION_TYPE"/>    
</class>

在此示例中,与 PersonRelation 类一样,属性 parentPersonId 是 Long 而不是 Person 类型,我得到 org.hibernate.MappingException: Association references unmapped class PersonRelation $ 请帮助。

4

2 回答 2

0

忘记按 id 引用。在 Hibernate 中,您使用的是对象,而不是表。我猜你的代码可以这样写:

@Entity  
@Table(name="your_table")  
public class Item{  

   private Long id;  
   private Item parentItem;  
   private List<Item> children;  

   @Id  
   @GeneratedValue(strategy=GenerationType.AUTO)  
   public Long getId(){  
   }  

   @ManyToOne()//Your options  
   public Item getParentItem(){  
   }  

   @OneToMane(mappedBy="parentItem")  
   public List<Item> getChildren(){  
   }  

   //Setters omitted  
}  
于 2012-07-20T12:24:41.193 回答
0

最后我找到了自己的答案。非常小的事情我们要做如下。

<class name="PersonRelation" table="PERSON_RELATION">
    <id name="id" column="IDENTIFIER">
        <generator class="native"/>
    </id>

   <!-- here remove many-to-one mapping ---- it's not needed-->
   <!-- treet participantPersonId as a simple property and everything will work --> 
    <Property name="parentPersonId" column="PARENT_PERSON_ID" type="Long"/>

    <Property name="childPersonId" column="CHILD_PERSON_ID"/>
    <property name="relationType" column="RELATION_TYPE"/>    
</class>

这工作得很好。:)

在这里,当您插入 Person 对象时,它也不会插入 PersonRelation 对象。您必须显式插入 PersonRelation 对象。也许,当我们检索 Person 对象时,它会为您提供 PersonRelation 的集合。这里不需要显式检索 PersonRelation 集合。

于 2012-07-21T12:25:19.610 回答