我想让hibernate
在以下映射上创建sql:
@Entity
public class MyBaseEntity {
@EmbeddedId
private MyEmbeddable id;
@ManyToMany
@JoinTable(name = "mybaseentity_mymode", //sets the linking table name
joinColumns = {
@JoinColumn(name = "fk_param1", referencedColumnName = "param2"), //@Id param
@JoinColumn(name = "fk_pram2", referencedColumnName = "param2")}, //@Id param
foreignKey = @ForeignKey(name = "fk_myembeddable_id")) //the contraint name
private Set<MyModes> modes;
}
@Embeddable
public class MyEmbeddable {
private String param1;
private String param2;
}
@Entity
public class MyMode {
@Id
private long id;
private String code;
}
每个MyBaseEntity
可以有多种模式。并且相同的MyMode
可以链接到多个基本实体。
问题:如何在自动生成的链接表中定义生成的CONSTRAINT
和UNIQUE
名称?
到目前为止,我使用了@JoinTable
和两个@JoinColumn
定义来设置@EmbeddedId
引用的约束。但是对MyMode
实体的外键约束名称引用仍然是自动生成的。
到目前为止生成的sql使用自动生成的名称:
CREATE TABLE public.mybaseentity_mymode
(
mybaseentity_param1 character varying(255) NOT NULL,
mybaseentity_param2 character varying(255) NOT NULL,
modes_id bigint NOT NULL,
CONSTRAINT mybaseentity_mymode_pkey PRIMARY KEY (mybaseentity_param1, mybaseentity_param2, modes_id),
CONSTRAINT fk9tr9k9gtbqcpvoxfv2hqop6ta FOREIGN KEY (modes_id)
REFERENCES public.mymode (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fk_myembeddable_id FOREIGN KEY (fk_param1, fk_param2)
REFERENCES public.mybaseentity (param1, param2) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
答案 0 :(得分:2)
我们通过以下方式定义自定义ForeignKey约束
您可以将@ForeignKey(name="something_something")
用于此目的。
您正在定义@OneToOne
,@ManyToOne
映射,您也可以使用@ForeignKey
中嵌入的@JoinColumn
,如下所示:
@JoinColumn(name = "your_id", foreignKey = @ForeignKey(name = "something_something"))
对于@ManyToMany
关系,您可以使用uniqueConstraints
中嵌入的foreignKey
,inverseForeignKey
和@JoinTable
但是,我不确定它是否会以您想要的方式定义约束。
答案 1 :(得分:1)
解决方案如下:使用inverse*
参数设置第二个约束。
@ManyToMany
@JoinTable(name = "mybaseentity_mymode", //sets the linking table name
joinColumns = {
@JoinColumn(name = "fk_param1", referencedColumnName = "param2"), //@Id param
@JoinColumn(name = "fk_pram2", referencedColumnName = "param2")}, //@Id param
foreignKey = @ForeignKey(name = "fk_myembeddable_id"), //the contraint name
inverseJoinColumns = @JoinColumn(name = "fk_mode", referencedColumnName = "id"),
inverseForeignKey = @ForeignKey(name = "fk_mode_id"))
private Set<MyModes> modes;