如何在链接表上设置hibernate生成的外键约束名?

时间:2016-11-16 11:10:41

标签: java hibernate

我想让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可以链接到多个基本实体。

问题:如何在自动生成的链接表中定义生成的CONSTRAINTUNIQUE名称?

到目前为止,我使用了@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
)

2 个答案:

答案 0 :(得分:2)

我们通过以下方式定义自定义ForeignKey约束 您可以将@ForeignKey(name="something_something")用于此目的。

您正在定义@OneToOne@ManyToOne映射,您也可以使用@ForeignKey中嵌入的@JoinColumn,如下所示:

@JoinColumn(name = "your_id", foreignKey = @ForeignKey(name = "something_something"))

对于@ManyToMany关系,您可以使用uniqueConstraints中嵌入的foreignKeyinverseForeignKey@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;