1

I have to generate a custom Auto Increment Which reset every day at time 00:00 to date prefixed auto increment value

for example Jan 9, 2016, the id should be in range 1601090001 to 1601099999, and Dec 15, 2016 t should be like 1612150001 to 1612159999.

Eg: Characteristics of 1612150001 are as below

  1. The id is an INT
  2. first two digit represent the year, 16 means 2016
  3. digits 3 and 4 denotes month,
  4. 5 and 6 represents date
  5. and remaining just a counter, so I expect we have less than 9999 records generated in a day.

How can I achieve this in JPA, what is the best way, currently i did it using another table to count the current value and using the last updated time and current time to compute the prefix and to decide the auto increment part to reset to 1 or not. Which i feel not a right solution.

IS there a way I can use @GeneratedValue annotation with a custom strategy to this, if so how can I do without causing an error, where it fails to generate an ID.

Ysak
  • 2,601
  • 6
  • 29
  • 53
  • Why there is no comments, is it because there is no direct solution or something else..... – Ysak Mar 21 '16 at 07:39
  • This is crazy, so there is no solution for this problem or no one known a direct solution...This is really crazy....Then I think then its time to adopt some other technologies than Java and Hibernate... – Ysak Apr 07 '16 at 18:23
  • Did you get this to work yet? – gustf Apr 12 '16 at 18:01
  • I didnt do it, since it took long time....to get this reply...currently i did it using a counter on a different table and things are working...I will try out the following way when i get a chance to refactor my existing code... – Ysak Apr 23 '16 at 13:14

1 Answers1

0

I found 2 options that would do the trick


You can use hibernate @GenericGenerator annotation and create a custom sequence generator. There is an example in this SO answer.


You can also use the JPA @PrePersist annotation.

@PrePersist
public void getNextIdFromGenerator() {
   id = yourInjectedGeneratorOrSomething.nextId(); 
} 
Community
  • 1
  • 1
gustf
  • 1,959
  • 13
  • 20