1

For a DB there are 4 columns that represent numbers:

col1 type: NUMBER(38)
col2 type: NUMBER(18) 
col3 type: NUMBER(10,2)  

In Spring JPA should I map these columns to Float or Double ?

@Column(name = "col1")
private Double col1

@Column(name = "col2")
private Double col2

@Column(name = "col3")
private Double col3

or

@Column(name = "col1")
private Float col1

@Column(name = "col2")
private Float col2

@Column(name = "col3")
private Float

Is it redundant to use Double as each number type

col1 type: NUMBER(38)
col2 type: NUMBER(18) 
col3 type: NUMBER(10,2)  

can be mapped to float without loss of precision ?

Update:

For NUMBER(38) should be ? :

@Column(precision=38, scale=0)

For NUMBER(10,2) should be ? :

@Column(precision=10, scale=2)
blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • You mean this - https://stackoverflow.com/questions/4078559/how-to-specify-doubles-precision-on-hibernate and this - https://www.tutorialspoint.com/hibernate/hibernate_mapping_types.htm? – Ajay Kumar Apr 05 '20 at 19:51
  • @AjayKumar please see question update. – blue-sky Apr 05 '20 at 19:55
  • 1
    Why not use `BigDecimal` together with the precision and scale values for the `@Column` annotation? – Matthew Formosa Apr 05 '20 at 20:19
  • @Matthew Formosa I plan to use Long, why BigDecimal instead of Long ? For NUMBER(38) Long is suitable with precision=38 ? – blue-sky Apr 05 '20 at 20:23
  • Yes, sure. However, if you're concerned about loss of precision with the other fields, I would definitely opt for `BigDecimal`. – Matthew Formosa Apr 05 '20 at 20:30
  • Having said that it could be the case that `Long` would not be able to store `NUMBER(38)` given its size so be careful. For such a use case there's `BigInteger` which might be a more suitable option. – Matthew Formosa Apr 05 '20 at 20:33
  • @Matthew Formosa Double is also an option instead of BigInteger? – blue-sky Apr 05 '20 at 20:43
  • It's an option but I would not go for `Double` given that you are not dealing with decimals in this case. – Matthew Formosa Apr 05 '20 at 20:48
  • Since NUMBER(38) and NUMBER(10,2) are huge, you can use Double for both. (Double should be capable of handling more precision in future if you need it). – Ajay Kumar Apr 06 '20 at 05:08

1 Answers1

0

The safest and most common way to do this is by using BigDecimal. Read more about BigDecimal : Here's a link!

Here is an example :

@Column(name = "EMPLOYEE_SALARY", precision = 10, scale = 2)
private BigDecimal salary;

Precision and Scale
Precision specifies total number of digits in a number
scale specifies number of digits after the decimal point.

Example 1
precision 6
scale 2

1234.54, 5432.12 are the valid numbers.

Example 2
precision 5
scale 0
12345, 65432, 98765 are the valid numbers````

Examples taken from :Here's [link](https://self-learning-java-tutorial.blogspot.com/2019/07/jpa-column-precision-specify-precision.html/)