How to create table with unidirectional relation in Hibernate?

i have the empty database in mysql, and two java entites. One of those have unidirectional relation. When hibernate tryes to create tables, i got the error:

Error executing DDL "alter table entry add constraint FK6ov2k83sx3crs9v3q8nvjuf1j foreign key (category_name) references category (name)" via JDBC Statement

There are my entites:

@Entity
public class Entry {
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY)
    private int id;

    @Column
    private String myfio;

    private String descr;

    @OneToOne(cascade = CascadeType.ALL)
    private Category category;
}

And the second:

@Entity
@Table(name="category")
public class Category {
    @Id
    @Column
    private String name;
}

How to create tables without errors?

>Solution :

OneToOne relationship shares the same id. So it should be the same type, but the first one is int (actually it should be Integer to allow null value for the transient (not stored) entities) and the second one is String. It seems you simply missed a line. Also, it worths to mention Vlad Mihalchea’s article https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/

Leave a Reply