spring-boothibernatespring-data-envers

Hibernate uses @JoinColumn as sequence name instead of table name


Recently migrated to spring boot 3 and have run into the following issue.

@Audited
@Entity
class ParentEntity {
...
@NotAudited
    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    @JoinColumn(name = "trace_info_id")
    @JsonIgnore
    private TraceInfo traceInfo;
}
@Entity
@Table(name = "trace_infos")
public class TraceInfo extends IDEntity {
...
}
@Audited(
    targetAuditMode = RelationTargetAuditMode.NOT_AUDITED
)
public class IDEntity {
    @Id
    @GeneratedValue
    private Integer id;
}

When I try to insert a record into ParentEntity class, hibernate looks for a sequence called trace_infos_seq, and cant find it. On startup the sequence it generates is called trace_info_id_seq. Is this expected behavior? How do I get it to look for the correct sequence?


Solution

  • In your code, you have defined a @OneToOne relationship between ParentEntity and TraceInfo using the @JoinColumn annotation. The @JoinColumn annotation specifies the name of the foreign key column in the owning entity's table that is used to establish the relationship.

    When you use @JoinColumn(name = "trace_info_id"), Hibernate understands that this column is a foreign key referencing the TraceInfo entity. However, Hibernate does not generate a sequence name based on the foreign key column name. Instead, it generates the sequence name based on the identifier column of the referenced entity (TraceInfo in this case).

    Since the identifier column of TraceInfo is id, Hibernate generates a sequence named trace_info_id_seq by default. This is why you're observing the behavior you mentioned.

    To resolve this issue, you can explicitly specify the sequence name using the @SequenceGenerator annotation on the TraceInfo entity:

    @Entity
    @Table(name = "trace_infos")
    @SequenceGenerator(name = "traceInfoSeq", sequenceName = "trace_info_id_seq", allocationSize = 1)
    public class TraceInfo extends IDEntity {
        // ... your entity code here ...
    }
    

    By adding the @SequenceGenerator annotation to the TraceInfo entity, you're instructing Hibernate to use the specified sequence name (trace_info_id_seq) for generating identifiers for the TraceInfo entity.

    Check this out: