Home > Mobile >  JPA modeling of FK pointing to various tables
JPA modeling of FK pointing to various tables

Time:03-25

There's a table with a "FK" column whose values might point back to either TableA or TableB, something like this:

CREATE TABLE TableC (
  "id" bigint GENERATED BY DEFAULT AS IDENTITY,
  "linked_entity_id" integer,
  "linked_entity_type" varchar(15),
  ...other columns
  PRIMARY KEY ("id")
);

I'm struggling with representing this in JPA. I'd like to have both TableA and TableB entities in JPA to have a List. Is there a way to do this?

This is my attempt, having TableC entity modeled like this:

@Entity
public class TableC {

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

    private Long linkedEntityId;

    @Enumerated(EnumType.STRING)
    private LinkedEntityType linkedEntityType;

    @ManyToOne
    @JoinColumn(name = "linked_entity_id", referencedColumnName = "id", insertable=false, updateable=false)
    private TableA tableA;

    @ManyToOne
    @JoinColumn(name = "linked_entity_id", referencedColumnName = "id", insertable=false, updateable=false)
    private TableB tableB;

}

But, what happens when the TableC has a row whose id in the linked_entity_id column belongs to TableA id not to TableB? I think an exception would be thrown.

PS: TableA and TableB do not have anything in common.

CodePudding user response:

You must use the @Where annotation:

@ManyToOne
@Where(clause = "linked_entity_type = 'TableA'")
@JoinColumn(name = "linked_entity_id", referencedColumnName = "id", insertable=false, updateable=false)
private TableA tableA;

@ManyToOne
@Where(clause = "linked_entity_type = 'TableB'")
@JoinColumn(name = "linked_entity_id", referencedColumnName = "id", insertable=false, updateable=false)
private TableB tableB;

Source: https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#pc-where

  • Related