[英]Generate long numeric id of type String with auto increment
我需要将具有ID(15-25位数字)的实体保存到H2
数据库。 由于db不支持BigInteger
(映射为Decimal
),因此保存此类长数字的唯一方法是String
类型。
问题:如何通过自动增量生成此类String
类型的数字ID?
UPDATE
ID应该类似于:123456789012345(最少15位,最多25位)
您仍然可以在后台使用BigInteger
。
这样的事情应该适用于任意数量的数字并且是线程安全的。
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());
}
}
如果您的限制(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());
}
}
请注意,为了进行测试,我将限制设置为2
和3
。 您可以调整自己的口味。
使用IDENTITY(START 10000000000),java Long,自动递增: http : //www.h2database.com/html/datatypes.html#identity_type
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.