[英]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.