3

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 Answer 1

5

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Another possible approach is to write a class that extends PGobject to provide an implementation of the range type, and a method that takes a Range<T> as a ctor argument. This would be cleaner, strictly, than baking details of PostgreSQL's range type representation into the Range<T> class.
@CraigRinger I agree with you. I didn't know about the PGobject. Thanks for your opinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.