简体   繁体   English

日期前缀自动增量id在JPA + Hibernate中

[英]date prefix auto increment id In JPA + Hibernate

I have to generate a custom Auto Increment Which reset every day at time 00:00 to date prefixed auto increment value 我必须生成一个自定义的自动增量,该增量每天在时间00:00重置为前缀的自动增量值

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. 例如,2016年1月9日,ID的范围应为1601090001至1601099999,2016年12月15日的ID范围应为1612150001至1612159999。

Eg: Characteristics of 1612150001 are as below 例如:1612150001的特性如下

  1. The id is an INT id是一个INT
  2. first two digit represent the year, 16 means 2016 前两位数字代表年份,16表示2016
  3. digits 3 and 4 denotes month, 数字3和4表示月份,
  4. 5 and 6 represents date 5和6代表日期
  5. and remaining just a counter, so I expect we have less than 9999 records generated in a day. 并只剩下一个计数器,因此我希望一天之内生成的记录少于9999个。

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. 如何在JPA中实现此目标,最好的方法是什么,目前,我使用另一个表来对当前值进行计数,并使用上次更新时间和当前时间来计算前缀并确定自动递增部分以将其重置为1或不。 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. 有没有一种方法可以将@GeneratedValue注释与自定义策略一起使用,如果可以的话,该如何做而又不会导致错误(无法生成ID)。

I found 2 options that would do the trick 我找到了两个可以解决问题的方法


You can use hibernate @GenericGenerator annotation and create a custom sequence generator. 您可以使用hibernate @GenericGenerator批注并创建一个自定义序列生成器。 There is an example in this SO answer . 这样的答案中有一个例子


You can also use the JPA @PrePersist annotation. 您还可以使用JPA @PrePersist批注。

@PrePersist
public void getNextIdFromGenerator() {
   id = yourInjectedGeneratorOrSomething.nextId(); 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM