为什么休眠会产生不必要的约束?

kde*_*980 1 java hibernate jpa

我在 Hibernate 中由双向关系生成的 SQL 有一个奇怪的问题。这是代码。

首先是@OneToMany侧面:

@Entity
@Table(name = "employers")
public class Employer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "eid")
    private Long employerId;
    
    private String name;
    
    @OneToMany(mappedBy = "titleId")
    private Set<Title> titles = new TreeSet<>(); 
    
    // Getters/setters...
}
Run Code Online (Sandbox Code Playgroud)

@ManyToOne方:

@Entity
@Table(name = "titles")
public class Title {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "tid")
    private long titleId;
    
    /**
     * Not sure if I need a bi-directional relation here.
     */
    @ManyToOne
    @JoinColumn(name = "employerId")
    private Employer employer;

    // Getters/setters...
}
Run Code Online (Sandbox Code Playgroud)

我对 springboot 和 hibernate 相当陌生,所以这是我尝试的第一件事,它实际上可以运行。根据我参考的教程和文档,在我的案例中生成的 SQL 是错误的。

这是生成的 SQL ( Postgres9Dialect)

CREATE TABLE public.items
(
    item_id bigint NOT NULL DEFAULT nextval('items_item_id_seq'::regclass),
    text character varying(255) COLLATE pg_catalog."default",
    title_tid bigint,
    CONSTRAINT items_pkey PRIMARY KEY (item_id),
    CONSTRAINT fkkwhqrl3vscoqcacws6kgsdlx5 FOREIGN KEY (item_id)
        REFERENCES public.titles (tid) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION,
    CONSTRAINT fkluhgxmnakeuroph186b2k05eq FOREIGN KEY (title_tid)
        REFERENCES public.titles (tid) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
)
Run Code Online (Sandbox Code Playgroud)

问题是这个约束:

CONSTRAINT fkkwhqrl3vscoqcacws6kgsdlx5 FOREIGN KEY (item_id)
REFERENCES public.titles (tid) MATCH SIMPLE
   ON UPDATE NO ACTION
   ON DELETE NO ACTION,
Run Code Online (Sandbox Code Playgroud)

如果头衔 id ( tid) 超过雇主 id 的最大数量(雇主表中的 eid),它的作用是不允许创建额外的头衔。生成的雇主表是正确的。

如果我手动删除此约束,则它会按预期工作。

为什么要创建这个错误的约束?我错过了什么?

(顺便说一句,标题是指特定雇主的标题,而不是书名,所以我不想将雇主和作者教程结合起来)

Ste*_*rnK 5

您应该以这种方式更正您的映射:

@Entity
@Table(name = "employers")
public class Employer {
    @OneToMany(mappedBy = "employer")
    private Set<Title> titles = new TreeSet<>(); 
    // ...
}

@Entity
@Table(name = "titles")
public class Title {

    @ManyToOne
    @JoinColumn(name = "employerId")
    private Employer employer;
    // ...
}
Run Code Online (Sandbox Code Playgroud)

mappedBy应持有协会的另一边的字段名。