[英]Generate long numeric id of type String with auto increment
I need to save entity with numeric id(15-25 digits) to H2
db. 我需要将具有ID(15-25位数字)的实体保存到
H2
数据库。 Since db doesn't support BigInteger
(it's mapped to Decimal
), the only way to save such long numbers is String
type. 由于db不支持
BigInteger
(映射为Decimal
),因此保存此类长数字的唯一方法是String
类型。
Question: How I can generate such a numeric id of String
type with auto increment? 问题:如何通过自动增量生成此类
String
类型的数字ID?
UPDATE UPDATE
ID should looks like: 123456789012345 (min 15 digits, max 25 digits) ID应该类似于:123456789012345(最少15位,最多25位)
You can still use a BigInteger
behind the scenes. 您仍然可以在后台使用
BigInteger
。
Something like this should work for any number of digits and is thread safe. 这样的事情应该适用于任意数量的数字并且是线程安全的。
private static final AtomicReference<BigInteger> id = new AtomicReference<>(BigInteger.ZERO);
public String nextId() {
BigInteger next = id.accumulateAndGet(BigInteger.ONE, (x, y) -> x.add(y));
return next.toString();
}
public void test(String[] args) {
for ( int i = 0; i < 100; i++ ) {
System.out.println(nextId());
}
}
If your limits (15 - 25 digits) is hard then something like this would probably do. 如果您的限制(15到25位数字)比较难,则可能会这样。
private static final int MIN_DIGITS = 2;
private static final int MAX_DIGITS = 3;
private static final BigInteger start = BigInteger.TEN.pow(MIN_DIGITS-1);
private static final BigInteger limit = BigInteger.TEN.pow(MAX_DIGITS).subtract(BigInteger.ONE);
private static final AtomicReference<BigInteger> id = new AtomicReference<>(start);
public String nextId() {
BigInteger next = id.accumulateAndGet(BigInteger.ONE, (x, y) -> {
if(x.compareTo(limit) >= 0) {
// Back to start.
return start;
}
return x.add(y);
});
return next.toString();
}
public void test(String[] args) {
for ( int i = 0; i < 1000; i++ ) {
System.out.println(nextId());
}
}
Note that for testing I have set the limits to 2
and 3
. 请注意,为了进行测试,我将限制设置为
2
和3
。 You can adjust to your taste. 您可以调整自己的口味。
使用IDENTITY(START 10000000000),java Long,自动递增: http : //www.h2database.com/html/datatypes.html#identity_type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.