Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a 32 digits numeric in Java and PostgreSQL?

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;
}
like image 280
cy221 Avatar asked May 19 '15 07:05

cy221


1 Answers

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.

like image 99
ibre5041 Avatar answered Sep 30 '22 03:09

ibre5041