10

I'm working on legacy system, need to read some of the info from database. Below are the table relationship

Vendor (vendorId - pk, vendorEid, name)
VendorContactBridge (bridgeId -pk, vendorEid, contactEid)
Contact (contactId -pk, contactEid, phone)

vendorEid and contactEid are not the primary key of the table but used as join column in Join table VendorContactBridge.

Vendor Entity -

@Entity
@Table(name="Vendor")
public class Vendor implements Serializable{

@Id
@Column(name="VENDORID")
private BigDecimal vendorId;

@Column(name="VENDOREID")
private BigDecimal vendorEid;

@OneToMany(fetch = FetchType.EAGER)
@JoinTable(name="VENDORCONTACTBRIDGE", 
joinColumns={@JoinColumn(name="VENDOREID", referencedColumnName="VENDOREID")},
inverseJoinColumns={@JoinColumn(name="CONTACTEID", referencedColumnName="CONTACTEID")})
private Set<Contact> vendorContact;
}

Contact Entity -

@Entity
@Table(name="CONTACT")
public class Contact implements Serializable{

@Id
@Column(name="CONTACTID")
private BigDecimal contactId;

@Column(name="CONTATEID")
private BigDecimal contactEId;

@ManyToOne
@JoinTable(name="VENDORCONTACTBRIDGE", 
joinColumns={@JoinColumn(name="CONTACTEID", referencedColumnName="CONTATEID")},
inverseJoinColumns={@JoinColumn(name="VENDOREID", referencedColumnName="VENDOREID")})
private Vendor vendor;
 }

while running the query, getting below exception

SecondaryTable JoinColumn cannot reference a non primary key.

I removed the Eager fetch which i have given in Vendor entity, i dont get any exception but it doesn't load the collection. What's wrong with association ?

4

2 回答 2

11

根据JPA 2.0 规范第 11.1.21 段 JoinColumn annotaion on page 379

对不是被引用表的主键列的被引用列的支持是可选的。使用此类映射的应用程序将不可移植。

似乎 Hibernate 选择不实现这个可选部分。其他实现可能。我在 EclipseLink 上试过,但那个也不起作用(验证失败)。

我看到两个解决方法。一种是调整您的架构以使用主键,从数据库设计理论的角度来看,这将是正确的事情。然而,这可能不是一个选项,因为其他软件依赖于这个模式,这留下了选项二。通过不在 JPA 中修改关系来解决它,只需使用 eid 并自己检索相关对象。

于 2012-12-16T08:41:09.743 回答
1

我找到了解决这个问题的方法。

看这里:

于 2014-06-03T13:20:33.523 回答