在 ManyToMany 中重命名外键约束

问题描述

spring-boot-starter-parent 2.4.1

spring-boot-starter-data-jpa

header=None

结果:

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "clients__semantics_permissions",joinColumns = {
       @JoinColumn(name = "client_id",foreignKey = @ForeignKey(name = "client_fk"))
    }
)
private Set<LevelTwoBase> semantics_level_two_base = new HashSet<LevelTwoBase>();
# \d clients__semantics_permissions
Table "public.clients__semantics_permissions"
               Column            |  Type   | Collation | Nullable | Default 
    -----------------------------+---------+-----------+----------+---------
     client_id                   | integer |           | not null | 
     semantics_level_two_base_id | integer |           | not null | 

我不知道如何重命名 Indexes: "clients__semantics_permissions_pkey" PRIMARY KEY,btree (client_id,semantics_level_two_base_id) Foreign-key constraints: "fk5nepw5pnbbeewptg0a3tft563" FOREIGN KEY (semantics_level_two_base_id) REFERENCES semantics__level_two_base(id) "semantics_fk" FOREIGN KEY (client_id) REFERENCES clients__branch(id) 的外键。换句话说,我就是不喜欢那个semantics_level_two_base_id

解决方法

指定 inverseForeignKey

@ManyToMany(fetch = FetchType.LAZY)                                                                         
@JoinTable(name = "clients__semantics_permissions",joinColumns = { @JoinColumn(name = "client_id",foreignKey = @ForeignKey(name = "client_fk")) },inverseForeignKey = @ForeignKey(name = "<the name you like>"))                                    
private Set<LevelTwoBase> semantics_level_two_base = new HashSet<LevelTwoBase>();                           

用于创建架构的休眠输出:(使用 level_two_base_fk 作为名称)

Hibernate: create table clients__semantics_permissions (client_id int8 not null,semantics_level_two_base_id int8 not null,primary key (client_id,semantics_level_two_base_id))
Hibernate: create table foo (id int8 not null,primary key (id))
Hibernate: create table level_two_base (id int8 not null,primary key (id))
Hibernate: alter table clients__semantics_permissions add constraint level_two_base_fk foreign key (semantics_level_two_base_id) references level_two_base
Hibernate: alter table clients__semantics_permissions add constraint client_fk foreign key (client_id) references foo