How to manually set a value for @GeneratedValue

1.6k Views Asked by At

Have a Spring boot with Spring Data JPA. Postgres DB.

General entity:

@Entity
@Table
class Entity {

@Id
@GeneratedValue
private int id;

}

when I try to make an entry with a specified id value, as a result I see that it is ignored and generated by @GeneratedValue.

How to overcome this?

1

There are 1 best solutions below

0
On

Posting the solution, to which I came after doing a debug of the whole persist process (not stating that this is the right way, but I literally didn't find any spot of "maybe I configured something wrong"):

public class MyGenerator extends SequenceStyleGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        return Optional.of(object)
                .filter(Entity.class::isInstance)
                .map(Entity.class::cast)
                .map(Entity::getId)
                .filter(i -> i > 0)
                .map(Serializable.class::cast)
                .orElseGet(() -> super.generate(session, object));
    }
)

and the entity:

@Entity
class Entity implements Serializable {

@GenericGenerator(name = "myGenerator", strategy = "org.a.b.c.generators.MyGenerator")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "myGenerator")
    private Integer id;

}