我需要将具有数字 ID(15-25 位数字)的实体保存到 H2
数据库。由于db不支持BigInteger
(它映射为Decimal
),因此保存这么长的数字的唯一方法是String
类型。
问题:如何生成这样一个自动递增的String
类型的数字id?
更新
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
。您可以根据自己的口味进行调整。
关于java - 生成具有自动增量的 String 类型的长数字 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48882736/