我有Application实体,想在JPA中表达与属性的自我双向关系。 EX。 QuoteStore(提供商应用程序)为在线门户和许多(消费者应用程序)提供服务 和QuoteStore(消费者应用程序)消耗来自Siebel CRM和许多(提供者应用程序)的服务 当关系是ManyToMany而不是self(例如App2DB或App2BizCase)时,上述方法很有效 对于自身双向ManyToMany与应用程序实体上的属性的关系;我将它分解为两个OneToMany关系,如
App 1--One2Many--* App2AppLink *--ManyToOne-1 App
(Provider 1--One2Many--* App2AppLink *--ManyToOne-1 Consumer)
这是Application Entity
@Entity
public class ApplicationEO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
/**
* This application instance services are consumed by Set<App2AppLinkEO> applications connections/links
*/
@OneToMany(mappedBy = "provider")
private Set<App2AppLinkEO> consumberLinks;
/**
* This application instance consumes services by Set<App2AppLinkEO> applications connections/links
*/
@OneToMany(mappedBy = "consumer")
private Set<App2AppLinkEO> providerLinks;
}
这是Application to Application关系表
@Entity
@Table(name="APP2APPLINK")
public class App2AppLinkEO {
@EmbeddedId
@AttributeOverrides({@AttributeOverride(name = "entity1Id", column = @Column(name = "PROVIDER_ID")),
@AttributeOverride(name = "entity2Id", column = @Column(name = "CONSUMBER_ID"))})
private CompositePK id;
@ManyToOne(optional = false)
private ApplicationEO providerApp;
@ManyToOne(optional = false)
private ApplicationEO consumerApp;
private String service;
private String status;
private String platform;
}
这是复合主键代码
@Embeddable
public class CompositePK implements Serializable {
private long entity1Id;
private long entity2Id;
}
以上设置生成关系表:
CREATE TABLE APP2APPLINK (
PLATFORM VARCHAR(255),
STATUS VARCHAR(255),
SERVICE VARCHAR(255),
PROVIDER_ID BIGINT NOT NULL,
CONSUMBER_ID BIGINT NOT NULL,
CONSUMERAPP_ID BIGINT,
PROVIDERAPP_ID BIGINT,
PRIMARY KEY (PROVIDER_ID, CONSUMBER_ID))
但为什么我会在下面看到额外的列?
CONSUMERAPP_ID BIGINT,
PROVIDERAPP_ID BIGINT,
答案 0 :(得分:1)
您没有在@ ManyToOne上设置@JoinColumn,因此他们获得默认的连接列名称。你需要给予,
@JoinColumn(name="PROVIDER_ID", insertable=false, updateable=false)
@JoinColumn(name="CONSUMBER_ID", insertable=false, updateable=false)
当您从EmbeddedId编写字段时,您需要将它们标记为只读(或者您可以将其标记为insertable = false,updateable = false)
但实际上你应该完全删除EmbeddedId并将@Id添加到@ ManyToOne并定义@IdClass。