Search code examples
jpainheritancemany-to-manyquarkussqlexception

Foreign Key violation on ManyToMany with inheritance


Im currently building the following scenario: I have an Action which holds a list of Parameters. Those can be in other actions as well, so I have a ManyToMany relationship. The Parameter is an abstract class, one implementation is a TextParameter. So now I have the following code:

@Data
@Entity
public class Action {
  
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
  @JoinTable(
     name = "Action2ParameterMapping",
     joinColumns = @JoinColumn(name = "actionId"),
     inverseJoinColumns = @JoinColumn(name = "parameterId"))
  private List<Parameter> parameters;
}

with Parameter as

@Data
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class ProductSample {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  ...
}

And TextParameter:

@Data
@Entity
@PrimaryKeyJoinColumn(name = "parameterId")
public class TextParameter extends Parameter {
  ...
}
 

I now created the Tables as follows (I don't want to generate since we use Flyway migration):

CREATE TABLE Action
(
  id    BIGINT NOT NULL PRIMARY KEY IDENTITY
)

CREATE TABLE Parameter
(
  id    BIGINT       NOT NULL PRIMARY KEY IDENTITY
)

CREATE TABLE TextParameter
(
  parameterId BIGINT NOT NULL FOREIGN KEY REFERENCES Parameter (id)
)

-- Many-To-Many MappingTable
CREATE TABLE Action2ParameterMapping
(
  actionId    BIGINT NOT NULL FOREIGN KEY REFERENCES Action (id),
  parameterId BIGINT NOT NULL FOREIGN KEY REFERENCES Parameter (id),
  PRIMARY KEY (actionId, parameterId)
)

I use Quarkus and have the simple PanacheRepository

@ApplicationScoped
public class ActionRepository implements PanacheRepository<Action> {
}

So now, when I now create an Action-Object holding Parameter-Objects and persist it using actionRepository.persist(action), I get an SQLServerException The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Action2Pa__actio__4242D080 and I don't understand why.

I understand that it tries to tell me, that it wanted to persist an entry in the MappingTable but the actionId did not belong to any Action, but how can that be? I don't understand, why this won't work.


Solution

  • After having the problem for over 3 days, I've solved almost right after asking the question...

    The problem was within the DB-Test-Suite. The @AfterEachmethod tried to delete parameters, which violated the Contraint...