简体   繁体   中英

What Java data type corresponds to the Oracle SQL data type NUMERIC/DECIMAL and get equivalent Java code for PLSQL?

I was looking for Java data type corresponding to the Oracle SQL data type NUMERIC/DECIMAL.

I got from web and other documents that java.math.BigDecimal is recommended for same. See one document.

http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/guide/jdbc/getstart/mapping.doc.html

The recommended Java mapping for the DECIMAL and NUMERIC types is java.math.BigDecimal, a Java type that also expresses fixed-point numbers with absolute precision. The java.math.BigDecimal type provides math operations to allow BigDecimal types to be added, subtracted, multiplied, and divided with other BigDecimal types, with integer types, and with floating point types.

The method recommended for retrieving DECIMAL and NUMERIC values is ResultSet.getBigDecimal. JDBC also allows access to these SQL types as simple Strings or arrays of char. Thus, Java programmers can use getString to receive a DECIMAL or NUMERIC result. However, this makes the common case where DECIMAL or NUMERIC are used for currency values rather awkward, since it means that application writers have to perform math on strings. It is also possible to retrieve these SQL types as any of the Java numeric types.

My final aim to transform Oracle PLSQL logic into equivalent java code. I tried to explain with sample logic.

See example Below :

In Oracle :

DECLARE
    inv_quantity_Balance DECIMAL(10,2);
BEGIN

WHEN (inv_quantity_Balance <= 1) THEN
      inv_quantity_Balance := 2;
ELSE
      inv_quantity_Balance := 3;
END;

Java :

BigDecimal  inv_quantity_Balance  = null ;
if ((inv_quantity_Balance <= 1)) {
    inv_quantity_Balance = 2 ;
}else {
    inv_quantity_Balance = 3 ;
}  

It shows complier error :

The operator <= is undefined for the argument type(s) BigDecimal, int
Type mismatch: cannot convert from int to BigDecimal

This is just one sample. Please help me finding java equivalent for the same. How can I preserve precision and scale etc ?

Oracle's NUMERIC and DECIMAL can indeed be mapped to java.math.BigDecimal .

The error you are getting has nothing to do with this mapping. It has to do with the fact that the operator <= is not defined for BigDecimal s. Comparisons are done with the compareTo method, like this:

BigDecimal balance = getSomeBigDecimal();
if (balance.compareTo(BigDecimal.ONE) <= 0) { // lower or equals
    balance = BigDecimal.valueOf(2);
} else {
    balance = BigDecimal.valueOf(3);
}  

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM