我有一个非常具体的场景如下。
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 $ 请帮忙。
答案 0 :(得分: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
}
答案 1 :(得分: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集合。