Reputation: 5136
During my app startup hibernate is altering my table by adding new constraints. Here is the sample code to get the complete picture of my problem.
Postgresql schema
create table public."A" {
a_id serial primary key
}
create table public."B" {
b_id serial primary key
}
create table public."C"(
a_id integer not null references public."A" (a_id),
b_id integer not null references public."B" (b_id),
)
DB models
class A{
@Id
@Column(name = "a_id")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
public Integer aId;
}
class B {
@Id
@Column(name = "b_id")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
public Integer bId;
}
class C {
@ManyToOne
@JoinColumn(name = "a_id")
public A a;
@ManyToOne
@JoinColumn(name = "b_id")
public B b;
}
At my app startup, it is creating the constraints again.
Hibernate: alter table public."C" add constraint FKk4caeiw8tynv7g0p13h5inaht foreign key (a_id) references public."A"
Hibernate: alter table public."C" add constraint FK4bsokehyo37wygp12onlu8fbl foreign key (b_id) references public."B"
In DB I see that the constraints are already availble
CONSTRAINT "C_a_id_fkey" FOREIGN KEY (a_id)
REFERENCES public."A" (a_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT "C_b_id_fkey" FOREIGN KEY (b_id)
REFERENCES public."B" (b_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
In addition to these I see 2 new constraints
CONSTRAINT FKk4caeiw8tynv7g0p13h5inaht foreign key (a_id)
REFERENCES public."A" (a_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT FK4bsokehyo37wygp12onlu8fbl foreign key (b_id)
REFERENCES public."B" (b_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
What could be wrong here?
Upvotes: 0
Views: 612
Reputation: 21143
That is because Hibernate is comparing the constraint names and noticing that no constraint exists for the specified names, thus it recreates it thinking that it doesn't exist.
One workaround is to manually specify the constraints by name in the annotations:
@JoinColumn(name = "...", foreignKey = @ForeignKey(name = "..."))
NOTE: There were some problems with versions of Hibernate up to 5.2.7 where certain annotations did not adhere to passing the foreign key annotated values correctly to the database schema tooling. I believe @JoinColumn
was fine but in case it wasn't, using 5.2.8 has all the fixes i introduced to avoid those annotations being ignored.
Another workaround would be obviously to remove the existing constraints and simply allow Hibernate to add them back using its own naming strategy.
Upvotes: 1