Persists Java object in postgresql in a range type

爷,独闯天下 提交于 2019-12-11 12:55:03

问题


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);
    }
}


来源:https://stackoverflow.com/questions/32114801/persists-java-object-in-postgresql-in-a-range-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!