I need to save entity with numeric id(15-25 digits) to H2
db. Since db doesn't support BigInteger
(it's mapped to Decimal
), the only way to save such long numbers is String
type.
Question: How I can generate such a numeric id of String
type with auto increment?
UPDATE
ID should looks like: 123456789012345 (min 15 digits, max 25 digits)
You can still use a BigInteger
behind the scenes.
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.
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
. You can adjust to your taste.
使用IDENTITY(START 10000000000),java Long,自动递增: http : //www.h2database.com/html/datatypes.html#identity_type
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.