【问题标题】:Hibernate foreign key to serial column休眠外键到串行列
【发布时间】:2016-07-13 01:18:04
【问题描述】:

Hibernate 生成奇怪的 DDL 用于配置串行列和 FK。示例(Book.author *-1 Authors.id):

@Entity
@Table(name = "books")
public class Book {
    private Integer id;
    private Author author;

    @Id
    @Column(name = "id", columnDefinition = "serial")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @JoinColumn(name = "author", nullable = true)
    @ManyToOne(optional = true, fetch = FetchType.LAZY)
    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }
}

@Entity
@Table(name = "authors")
public class Author {
    private Integer id;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
}

books 表中作者列的结果 DDL:

ALTER TABLE books ADD COLUMN author integer;
ALTER TABLE books ALTER COLUMN author SET NOT NULL;
ALTER TABLE books ALTER COLUMN author SET DEFAULT nextval('authors_seq'::regclass);

它有奇怪的默认值,我也不能让它为空。是否可以在不为 FK 编写 columnDefinition 的情况下修复它?

【问题讨论】:

  • 我认为你在这里犯了错误@JoinColumn(name = "author", nullable = true) 请试试这个@JoinColumn(name = "id", nullable = false)
  • @RaviKavaiya name 只是列的名称,可以是任何名称。
  • 关于这个问题的老问题stackoverflow.com/questions/15511899/…
  • 只能使用@ManyToOne(cascade = CascadeType.ALL) 不用写列注解
  • 看起来像休眠中的一个错误,所以除非已经报告,否则请报告它。其他 JPA 提供程序在这方面工作得很好

标签: java hibernate postgresql jpa


【解决方案1】:

我已将其报告为错误https://hibernate.atlassian.net/browse/HHH-10647。当前的解决方法是对 FK 列使用 columnDefinition:columnDefinition = "integer"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    相关资源
    最近更新 更多