Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA or Hibernate to generate a (non primary key) column value, not starting from 1

I want a JPA/Hibernate (preferably JPA) annotation that can generate the value of a column, that is not a primary key and it doesn't start from 1.

From what I have seen JPA cannot do that with @GeneratedValue and @SequenceGenerator and @TableGenerator. Or with anything else.

I have seen a solution with an extra table, which I find is not elegant.

I can live with a Hibernate annotation, because I already have hibernate annotations.

I want to use @Generated but I cannot make it work and people claim that it is possible.

@Generated(GenerationTime.INSERT)
private long invoiceNumber;//invoice number

Update: an extra requirement, if the transaction is rolled back, we can't have a gap in the numbering. Anyone?

like image 750
mist Avatar asked Dec 25 '22 20:12

mist


1 Answers

The @GeneratedValue only works for identifiers and so you can't use it. If you use MySQL, you are quite limited, since database sequences are not supported.

InnoDB doesn't support multiple AUTO_INCREMENT columns and if your table PK is AUTO_INCREMENTED, then you have two options:

  1. Go for a separate table that behaves like a sequence generator, the solution you already said you are not happy about.

  2. Use an INSERT TRIGGER to increment that column.

like image 60
Vlad Mihalcea Avatar answered Dec 30 '22 12:12

Vlad Mihalcea