【发布时间】:2020-04-06 01:33:24
【问题描述】:
我想在我的实体之间建立多对多关系。 我想让hibernate自动生成这个表,但这不会发生。 这是我的实体:
DrugsEntity:
@Entity
@Table(name = "drugs", schema = "meds", catalog = "chinamed")
public class DrugsEntity {
@Id
@Basic
@Column(name = "id")
private int id;
@Basic
@Column(name = "name_eng")
private String nameEng;
@ManyToMany()
@JoinTable(name = "drug_symptom",
joinColumns = { @JoinColumn(name = "drug_id",nullable = false) },
inverseJoinColumns = { @JoinColumn(name = "symptom_id", nullable = false) })
private Set<SymptomEntity> symptoms;
}
症状实体:
@Entity
@Table(name = "symptom",schema = "meds", catalog = "chinamed")
public class SymptomEntity {
@Id
@GeneratedValue
int id;
@Basic
String name;
@Column
@ManyToMany(mappedBy = "symptoms",cascade = CascadeType.ALL)
Set<DrugsEntity> drugs;
}
一些配置:
jpa:
hibernate:
ddl-auto: update
show-sql: true
所以我可以看到休眠 sql 查询:
Hibernate: create table meds.diseases (disease_id int4 not null, drug_id int4, name varchar(255), primary key (disease_id))
Hibernate: create table meds.drugs (id int4 not null, action_pharm varchar(255), action_tkm varchar(255), clinic varchar(255), contraindications varchar(255), form varchar(255), maker varchar(255), name_eng varchar(255), name_ru varchar(255), taking_method varchar(255), primary key (id))
Hibernate: create table meds.herbal_drug (herbal_id int4 not null, drug_id int4, primary key (herbal_id))
Hibernate: create table meds.pattern_drug (pattern_id int4 not null, drug_id int4, primary key (pattern_id))
Hibernate: create table meds.symptom (id int4 not null, name varchar(255), primary key (id))
Hibernate: alter table if exists symptom_drug add constraint FKl7jx9kgpfiunb1r5neejqi1in foreign key (drug_id) references meds.symptom
Hibernate: alter table if exists symptom_drug add constraint FKimmnf4263cgg3yg46i90tkn1g foreign key (symptom_id) references meds.drugs
Hibernate: alter table if exists symptom_drugs add constraint FKnvs2tystmth11i573t29rtayk foreign key (drugs_id) references meds.drugs
Hibernate: alter table if exists symptom_drugs add constraint FKng4i6ig5nr2laew225ttfnrb9 foreign key (symptom_entity_id) references meds.symptom
正如我所见,hibernate 甚至不尝试创建此表。
Using dialect: org.hibernate.dialect.PostgreSQL10Dialect
如何实现hibernate自己创建该表?
P.S:已经看过这个链接Hibernate doesn't create join table 但我想这不是我的情况。
已解决: 问题是这张桌子已经装箱了。而且我可能会在 hibernate 的查询中注意到一些有趣的东西:在 drug_symptom 表名之前没有前缀“meds”。 所以它在数据库的“公共”模式中创建了表。 以这种方式解决:添加了 default_schema
spring:
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
default_schema: meds
但我也可以在注释@JoinTable 中使用“schema”参数。
【问题讨论】:
标签: java spring hibernate spring-boot jpa