Search code examples
javajdbcbigdecimalvert.x

insert BigDecimal to database with vertx-jdbc


I am using the vertx-jdbc-client (http://vertx.io/docs/vertx-jdbc-client/java/) for my database connection. This works fine for every data type except BigDecimal.

In my database the type is decimal(13,2), in Java I am using a BigDecimal data type. I just want to read & update this column with the vertx-jdbc-client.

Unfortunately I get following exception:

    SEVERE: Unhandled exception
java.lang.IllegalStateException: Illegal type in JsonObject: class java.math.BigDecimal
    at io.vertx.core.json.Json.checkAndCopy(Json.java:215)
    at io.vertx.core.json.JsonArray.add(JsonArray.java:444)

Looking at io.vertx.core.json.Json.checkAndCopy tells me that BigDecimal is not supported by the framework:

@SuppressWarnings("unchecked")
  static Object checkAndCopy(Object val, boolean copy) {
    if (val == null) {
      // OK
    } else if (val instanceof Number && !(val instanceof BigDecimal)) {
      // OK
    } else if (val instanceof Boolean) {
...
}

I googled a bit, but did not found an explanation why this not supported.

Is there a solution for this?

Following Versions are used: (Java 8, Vertx 3.5.0, Postgres 9.6)


Solution

  • You can convert your BigDecimal to String and then use the CAST function:

    INSERT INTO test (i) VALUES (CAST('3.235' AS DECIMAL))
    

    And to read it back:

    SELECT CAST(i AS TEXT) from test