Persists Java object in postgresql in a range type

2019-08-12 06:44发布

问题:

I have a Postgres table with several columns of type numrange and int4range.

I want to persist data in it from Java. Currently I have this data in a Java class like this:

class Range<T> {
    private Integer minimum;
    private Integer maximum;
    // more code...
}

I'm using the JDBC Driver and the java.sql.*and I've tried several things, without success:

pstmt.setObject(7, myObject.price()); // price() returns a Range object

This gives me the following error:

Can't infer the SQL type to use for an instance of com.scmspain.admatching.domain.Range. Use setObject() with an explicit Types value to specify the type to use.

I cannot specify the type, since it does not exist in the java.sql.Types class.

回答1:

It can be done by using the Types.OTHER.

pstmt.setObject(7, myObject.price(), Types.OTHER);

It was also required to include a toString() method in my Range class:

class Range<T> {
    // more code...

    public String toString() {
        return String.format("[%d, %d]", minimum, maximum);
    }
}