Reputation: 811
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?
Upvotes: 2
Views: 2069
Reputation: 811
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;
}
Upvotes: 3