Search code examples
javapostgresqljpaebean

JPA/Ebean - force @Id to strictly increment by +1 with PostgreSQL


I have the following Model:

public class Parameter extends Model {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public long id;
}

The records created by save() look like this:

play=> select id from parameter;
 id
----
  1
  2
  3
  4
  5
 21
(6 rows)

Is there a way that I can tell JPA to always increment the id by exactly one, instead of randomly jumping to 21?


Solution

  • What you are observing (jump to 21) is likely to be an implmentation detail of Ebean prior to 4.0.5. Ebean is using a 'fetch ahead' mechanism on the sequence. After 4.0.5 Ebean switched to use Postgres SERIAL by default (so by default you won't see this with Ebean/Postgres after 4.0.5). Refer: https://github.com/ebean-orm/avaje-ebeanorm/issues/97

    That all said - 'incrementing EXACTLY by 1' is something you generally want to avoid as it becomes a concurrency issue (avoid making the autoincrement ID transactional as that introduces contention). When you need 'increment exactly by one' semantics (like cheque numbers etc) then you can look to create in batch in advance.