I'm using JPA with a table-per-class inheritance strategy (joined inheritance), and I'm encountering a foreign key constraint issue when saving an entity. Below are the details of the problem:
Entities:
Connector
is the base entity. SinglePageConnector
and DualPageConnector
extend Connector
and are stored in separate tables (singlepage_connector
, dualpage_connector
). I have a UserConnector
entity that references Connector
via a foreign key (connector_id).
create table connector
(
id varchar(36) not null,
name varchar(255) not null,
login_page_url varchar(255),
primary key (id)
);
create table singlepage_connector
(
id varchar(36) not null,
connector_id varchar(36) not null,
primary key (id),
foreign key (connector_id) references connector(id)
);
create table dualpage_connector
(
id varchar(36) not null,
connector_id varchar(36) not null,
next_button_selector varchar(36),
primary key (id),
foreign key (connector_id) references connector(id)
);
create table user_connector
(
id varchar(36) not null,
user_id varchar(36) not null,
connector_id varchar(36) not null,
username varchar(255) not null,
PRIMARY KEY (id),
CONSTRAINT unique_user_connector UNIQUE (user_id, connector_id),
FOREIGN KEY (connector_id) references connector (id)
)
JPA entity code
@Entity
public class Connector {
@OneToMany(mappedBy = "connector")
private Set<UserSwaConnector> userSwaConnectors;
}
@Entity
public class SinglePageConnector extends Connector { ... }
@Entity
public class DualPageConnector extends Connector { ... }
@Entity
public class UserConnector {
@ManyToOne
@JoinColumn(name = "connector_id", referencedColumnName = "id")
private Connector connector;
...
}
Issue
When I try to save a UserConnector like this:
UserConnector connector = UserConnector.builder()
.username(command.getConnectorUsername())
.userId(command.getUserId())
.connector(connector)
.build();
userSwaConnectorRepository.save(connector);
I encounter the following error:
Cannot add or update a child row: a foreign key constraint fails (authorization.user_connector, CONSTRAINT user_connector_ibfk_1 FOREIGN KEY (connector_id) REFERENCES connector (id))
The error occurs because JPA is trying to insert the foreign key reference (connector_id) into the parent connector table, but the actual data is in one of the child tables (singlepage_connector or dualpage_connector). Since UserConnector references Connector, which is an abstract base class, JPA does not correctly search in the child tables for the foreign key.
What I want to do:
I want JPA to search for the connector_id in the appropriate child table (singlepage_connector or dualpage_connector) instead of the parent connector table, since the actual data is stored in those child tables.
How can I configure JPA to properly handle this foreign key relationship, considering that the actual data resides in the child tables?