Home > Software engineering >  JPA/Hibernate with externally generated identifiers
JPA/Hibernate with externally generated identifiers

Time:11-02

I'm expected to expose through Spring Boot 2.5 a legacy relational schema where the primary key is computed by the DBMS on the basis of an identity field along the following lines:

create table items
(

    serial      int identity,

    id          as '/items/'   convert(varchar(12), serial) persisted primary key,

    …

)

My issue is that JPA/Hibernate seem to assume that the primary key is always going to be generated on the server side and we don't apparently have a suitable generation strategy:

@Entity
@Table(name="items")
public static class ItemEntity {

    @Id
    @GeneratedValue(strategy="{???}")
    private String id;

    …

}

Any chances of instructing JPA/Hibernate just to accept the generated value without trying to write it?

CodePudding user response:

That's exactly what the IDENTITY strategy is for. This strategy assumes that the ID is generated in the database.

@Entity
@Table(name="items")
public static class ItemEntity {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private String handle;

    …

}
  • Related