H2, Spring Data with Hibernate 6. I like to control the “primary key” definition when I am using a @JoinTable
in my java model. The issue Hibernate seems to create automatically two separate primary key definitions instead of a single one where both foreign key columns get considered.
e.g. I have a “Layout” and “Module” class, where layouts can have multiple times and instance of the same “module” (Many-to-Many relationship).
@Entity
@Table(name="`layouts`")
@Data
public class Layout {
@Id
@GeneratedValue
private Integer id;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "layout_modules", joinColumns = { @JoinColumn(name = "layout_id") }, inverseJoinColumns = { @JoinColumn(name = "module_id") })
@OrderColumn(name = "sort", columnDefinition = "integer default 0", nullable = true)
private List<Module> modules = new ArrayList<>();
}
Based on the @JoinTable
Hibernate generates the “layout_modules” table with two “PRIMARY KEY” Definitions.
Current Generated DDL
CREATE TABLE "shop"."layout_modules" (
"layout_id" INTEGER NOT NULL,
"module_id" INTEGER NOT NULL,
"sort" INTEGER DEFAULT 0 NOT NULL,
CONSTRAINT "FKg1usbavp8i4rarv3unyx83fnq" PRIMARY KEY ("layout_id"),
CONSTRAINT "FKo1sjor3ruyi04m7dfurkgn4ru" PRIMARY KEY ("module_id"),
CONSTRAINT "FKg1usbavp8i4rarv3unyx83fnq" FOREIGN KEY ("layout_id") REFERENCES "shop"."layouts"("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT "FKo1sjor3ruyi04m7dfurkgn4ru" FOREIGN KEY ("module_id") REFERENCES "shop"."modules"("id") ON DELETE RESTRICT ON UPDATE RESTRICT
);
CREATE INDEX "FKg1usbavp8i4rarv3unyx83fnq_INDEX_8" ON "shop"."layout_modules" ("layout_id");
CREATE INDEX "FKo1sjor3ruyi04m7dfurkgn4ru_INDEX_8" ON "shop"."layout_modules" ("module_id");
BUT I like that only one single “PRIMARY KEY” definition should be created instead. Any idea how I can influence or enforce that?
If not easily possible can I somehow enforce that for @JoinTable
no primary key definitions get automatically created?
Expected DDL which I like to have generated
CREATE TABLE "shop"."layout_modules" (
"layout_id" INTEGER NOT NULL,
"module_id" INTEGER NOT NULL,
"sort" INTEGER DEFAULT 0 NOT NULL,
CONSTRAINT LAYOUT_MODULES_PK PRIMARY KEY ("layout_id","module_id"),
CONSTRAINT "FKg1usbavp8i4rarv3unyx83fnq" FOREIGN KEY ("layout_id") REFERENCES "shop"."layouts"("id") ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT "FKo1sjor3ruyi04m7dfurkgn4ru" FOREIGN KEY ("module_id") REFERENCES "shop"."modules"("id") ON DELETE RESTRICT ON UPDATE RESTRICT
);
CREATE UNIQUE INDEX PRIMARY_KEY_8 ON "shop"."layout_modules" ("layout_id","module_id");
CREATE INDEX "FKg1usbavp8i4rarv3unyx83fnq_INDEX_8" ON "shop"."layout_modules" ("layout_id");
CREATE INDEX "FKo1sjor3ruyi04m7dfurkgn4ru_INDEX_8" ON "shop"."layout_modules" ("module_id");