0

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?

MFEB
  • 131
  • 1
  • 8

1 Answers1

1

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:

Diego Borba
  • 1,282
  • 8
  • 22
  • This seems to work for one of my environments but not for the other, ive tried deleting the pgsql schema but it still wont generate the new sequence, is there a cache somewhere that I need to clear? – MFEB Aug 31 '23 at 21:45
  • If the sequence generation is working in one environment but not in another, it's possible that there might be some differences in the database configuration or schema. – Diego Borba Sep 01 '23 at 12:29