Hibernate通过非id列关联两个实体

时间:2014-03-07 09:24:03

标签: java hibernate orm mapping

我面临以下情况:

  

表存储:| Id | ... | CostCenterNumber |

     

表MasterData:| dennskdnr | ... |

我当前的映射如下所示

@Entity
@Table(name = "Store")
public class Store implements Identifiable {
[...]
    @OneToOne(optional = true)
    @JoinColumn(name = "CostCenterNumber", insertable = false, updatable = false)
    private MasterData masterData;
[...]
}

@Entity
@Table(name = "MasterData")
public class MasterData {
[...]
    @OneToOne(optional = true)
    @JoinColumn(name = "dennskdnr")
    private Store store;
[...]
}

引导我出现以下异常:

  

org.hibernate.TypeMismatchException:提供了错误类型的id   class datamodel.Store。预期:类java.lang.String,得到类   java.lang.Integer中

1 个答案:

答案 0 :(得分:2)

以下是关联的映射方式:

@Entity
@Table(name = "Store")
public class Store implements Identifiable {

    @OneToOne(optional = true)
    @JoinColumn(name = "CostCenterNumber", referencedColumnName="dennskdnr")
    private MasterData masterData;

}

@Entity
@Table(name = "MasterData")
public class MasterData {

    @OneToOne(optional = true, mappedBy = "masterData")
    private Store store;

}

记住:在双向关联中,总是有一个所有者方面,它定义了关联的映射方式,反面,使用必须使用mappedBy属性来说明: I'在反面,查看另一个实体中的“masterData”属性,以了解该关联的映射方式