我有一个非常具体的情况,如下。

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:关联引用未映射的类PersonRelation
$
请帮忙。

最佳答案

忘记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
}

10-06 16:21
查看更多