I have Application entity, want to express self bi-directional relationship with attribute in JPA. EX. QuoteStore(provider Application) provides services to online portal and many(consumer applications) and QuoteStore(consumer Application) consumes services from Siebel CRM and many (provider applications) The above approach works well when relationship is ManyToMany but not self (ex. App2DB or App2BizCase) For Self bidirectional ManyToMany relationship with attributes on application entity; I decomposed it to two OneToMany Relationships like
App 1--One2Many--* App2AppLink *--ManyToOne-1 App
(Provider 1--One2Many--* App2AppLink *--ManyToOne-1 Consumer)
Here is 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;
}
Here is Application to Application relationship table
@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;
}
And Here is Composite Primary Key code
@Embeddable
public class CompositePK implements Serializable {
private long entity1Id;
private long entity2Id;
}
Above setup generates relation table as:
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))
But why do I see below extra columns there?
CONSUMERAPP_ID BIGINT,
PROVIDERAPP_ID BIGINT,
You are not setting the @JoinColumn on the @ManyToOne's so they get the default join column name. You need to give,
You need to mark them as read-only as you are writing the field from your EmbeddedId (or you could mark it as insertable=false, updateable=false)
But really you should remove the EmbeddedId entirely and just add @Id to the @ManyToOne's and define an @IdClass.