0

My class is not Entity there is code fragment

@SequenceGenerator(name="seqUniqueKeyGenerator",sequenceName="SEQ_UNIQUE_KEY",allocationSize=1)
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="seqUniqueKeyGenerator")
@Id
private Integer sequenceId;

public Integer getSequenceId() {
    return sequenceId;
}

public void setSequenceId(Integer sequenceId) {
    this.sequenceId = sequenceId;
}

public static void main(String[] args) {
    UniqueKeyGenerator uniqueKeyGenerator = new UniqueKeyGenerator();
    System.out.println(uniqueKeyGenerator.getSequenceId());

}

I want retrieve nextVal like this, is it possible?

Tato
  • 195
  • 4
  • 17

2 Answers2

1

You can consume nextVal as mentioned in this thread but you have to consider it is consumed by means of a SQL sentence, which means this is a solution coupled to database.

I don't know a way to consume nextVal in such way you are asking above.

Community
  • 1
  • 1
malaguna
  • 4,183
  • 1
  • 17
  • 33
0

We all know the default behaviour of Hibernate when using @SequenceGenerator - it increases real database sequence by one, multiple this value by 50 (default allocationSize value) - and then uses this value as entity ID.

From G. Demecki

This means that the ID id not generated in your Java-Program. It is created in your database. So you can't read it before it is acutally generated in the database. You can guess it using the formula described by G.Demecki but that is certainly not the way to go. If you want the id of an entity just save it and read the id from the return value of save what should be the saved entity itself.

Community
  • 1
  • 1
SWiggels
  • 2,159
  • 1
  • 21
  • 35