I try to control the foreign key name generation using the @ForeignKey
annotation. This usually works well. But in a special case it does not what I want and I don't know how to configure it.
The special case is when I use @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
. When the base class has a @ManyToOne
relationship and I want to specify the foreign key name using @ForeignKey
it only applies for the base class.
+------------+ +--------------+
| BaseEntity | -----> | OtherEntity |
+------------+ +--------------+
^
|
+--------+---------+
+----------+ +----------+
|SubEntity1| |SubEntity2|
+----------+ +----------+
My BaseEntity
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Table(name = "base_entity")
public class BaseEntity {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(foreignKey = @ForeignKey(name = "FK_other_entity"))
private OtherEntity otherEntity;
}
My SubEntity1
(same for the the SubEntity2
)
@Entity
@Table(name = "sub_entity_1")
public class SubEntity1 extends BaseEntity {
}
and just to be complete .... the OtherEntity
:
@Entity
@Table(name = "other_entity")
public class OtherEntity {
@Id
@GeneratedValue
private Long id;
}
Hibernate will generate a ddl script containing the following foreign key definitions:
alter table base_entity
add constraint FK_other_entity
foreign key (otherEntity_id)
references other_entity (id);
alter table sub_entity_1
add constraint FK_jtmdc6tiytduxbpesmng9g3bk
foreign key (otherEntity_id)
references other_entity (id);
alter table sub_entity_2
add constraint FK_9xpb6q7qeq5r3pq071cbbiygx
foreign key (otherEntity_id)
references other_entity (id);
As you can see the sub entities foreign key name is random.
The sub entities don't have a field holding a reference to the OtherEntity
, so I can't place a @ForeignKey
annotation there.
How can I control the foreign key name for sub entities when using a table per class inheritence type?
I'm using
- spring-boot 1.4.3.RELEASE
- hibernate 5.6.2.Final
EDIT
I also tried to use @AssociationOverride
, but it does not work.
If you need a quick setup for schema generation you might want to take a look at my previous question Generate DDL with spring boot using a custom delimiter