Home > Software design >  HIbernate doesn't create Foreign key for @OneToOne
HIbernate doesn't create Foreign key for @OneToOne

Time:03-01

I have two tables:

@Entity
public class TestEntity {

    @Id
    @Column(name = "id")
    private UUID id;

    @OneToOne(targetEntity = InfoEntity.class, cascade = CascadeType.ALL)
    @JoinColumn(name="id", referencedColumnName = "id")
    private InfoEntity info;

    ...
}
@Entity
public class InfoEntity {
    @Id
    @Column(name = "id")
    private UUID id;

    @OneToOne(mappedBy = "info")
    private TestEntity test;
    
    ...
}

Basically I want to define a Foreign Key from TestEntity to InfoEntity by id fields which are the same in both tables. The problem is that when I check the database in IntelliJ Idea I don't see any Foreign Keys in keys section (checked both tables), only their PK's. Is something wrong with this code? I already set the property as it suggested in another similar question:

  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect

CodePudding user response:

The problem is that name in JoinColumn has value id. Change it to info_id for example:

@OneToOne(targetEntity = InfoEntity.class, cascade = CascadeType.ALL)
@JoinColumn(name="info_id", referencedColumnName = "id")
private InfoEntity info;

You TestEntity already has a column id, so it has to has another name.

  • Related