7

I'm developing a little tool with JavaFX and a PostgreSQL-database. My task now is to handle a 32 digits numeric. I tried it with Long, but its to short / small.

I remember that Postgres grumbled because I didn't use the correct datatype, that's why I'm asking here first, before I change all lines again affected by this problem.

I do not math with this numeric, but I need to save null within.

What's your advice? String, BigInteger?

Code-Example:

//...
myObject.setSerialNumber(getLongFromDB(rs, "serialnumber"));
//...

private static Long getLongFromDB(ResultSet rs, String column) throws SQLException {
    Long l = rs.getLong(column);
    if (rs.wasNull()) l = null; // because getLong is long not Long, I need to know about null
    return l;
}
4
  • Is this really a number or may it be a string containing only digits? Commented May 19, 2015 at 7:33
  • In database it's a "numeric(32)". Commented May 19, 2015 at 7:34
  • What is the parameter for your method setSerialNumber? Is it long? or is it of some other type so you are storing null? Commented May 19, 2015 at 7:44
  • It's setObject(Long l). Commented May 19, 2015 at 8:14

1 Answer 1

9

In case of Oracle/PostgreSQL the corresponding type to NUMBER/NUMERIC is Java's BigDecimal. The both types have the same internal representation (number stored as decimal digits). So you do not face any problems with rounding errors and also casting between them should be faster.

It is big misunderstanding that many Java developers use Int(s)/Long(s) for IDs because they were told that int/long is "much faster". In JEE you practically never perform any mathematical computations with NUMBERs returned from the database. Also up to some size BigDecimal is smaller that Long.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm using BigInteger now to get the numeric. And when I'm writing into database I create a new BigDecimal with the BigInteger parameter, because Postgres can't map BigInteger. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.