Igor Gorbunov
Igor Gorbunov

Reputation: 85

Negative Id values generation with GenerationType.SEQUENCE

Why do I always get negative values of an entity id? Wheter it related with increment amount value? For example while I'm using

create sequence message_sequence start 1 increment 1;

I always get negative values (-38, -44, -45). But in case I'm putting

create sequence message_sequence start 1 increment 50;

It's all fine (52, 102). Why so weird behavior? This is an entity:

@Entity
@Table(name = "messages")
public class Message {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "message_sequence")
    @SequenceGenerator(name = "message_sequence", sequenceName = "message_sequence")
    private long id;

    private String text;

    public void setText(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

programe entrance point:

EntityManagerFactory emf = JPAUtility.getEntityManagerFactory();

EntityManager entityManager = emf.createEntityManager();

entityManager.getTransaction().begin();

Message m = new Message();
m.setText("Hello World");

etityManager.persist(m);

entityManager.getTransaction().commit();
entityManager.close();

Upvotes: 0

Views: 3540

Answers (2)

K Kumar
K Kumar

Reputation: 141

After adding allocationSize = 1 code to @SequenceGenerator working fine!

Upvotes: 2

Gangadhar
Gangadhar

Reputation: 41

In SequenceGenerator annotation there is a variable named allocationSize. This size is by default is 50. It means that Hibernate will reserve 50 ids and it will not need to retrieve new id for every insert. set the allocationSize=1 to resolve this issue for negetive value generation.

Upvotes: 4

Related Questions