简体   繁体   中英

Hibernate foreign key to serial column

Hibernate generates strange DDL for configuration with serial column and FK to it. Example (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;
    }
}

Result DDL for column author in books table:

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);

It has strange default value and also i can't make it nullable. Is it possible to fix it without writing columnDefinition for FK?

I have reported it as a bug https://hibernate.atlassian.net/browse/HHH-10647 . Current workaround is using columnDefinition for FK column: columnDefinition = "integer"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM