JDBC中的Java类型为Postgres ltree

时间:2014-01-30 03:10:08

标签: java postgresql jdbc prepared-statement ltree

有谁知道什么Java类型映射到Postgres ltree类型?

我创建了一个这样的表:

CREATE TABLE foo (text name, path ltree);

一些插页:

INSERT INTO foo (name, path) VALUES ( 'Alice', 'ROOT.first.parent');
INSERT INTO foo (name, path) VALUES ( 'Bob', 'ROOT.second.parent');
INSERT INTO foo (name, path) VALUES ( 'Ted', 'ROOT.first.parent.child');
INSERT INTO foo (name, path) VALUES ( 'Carol', 'ROOT.second.parent.child');

那里没什么奇怪的。现在我想使用PreparedStatment批量处理它:

public final String INSERT_SQL = "INSERT INTO foo( name, path) VALUES (?, ?)";

public void insertFoos(final List<Foo> foos)
{
    namedParameterJdbcTemplate.getJdbcOperations().batchUpdate(INSERT_SQL, new BatchPreparedStatementSetter()
{
  @Override
  public void setValues(PreparedStatement ps, int i) throws SQLException
  {
    ps.setString(1, foos.get(i).getName());
    ps.setString(2, foos.get(i).getPath());
  }

  @Override
  public int getBatchSize()
  {
    return foos.size();
  }
});

}

这会产生以下错误:

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [INSERT INTO foo( name, path) VALUES (?, ?)]; nested exception is
  org.postgresql.util.PSQLException: ERROR: column "path" is of type ltree but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.

显然我错过了一些东西。为什么我可以使用纯SQL而不是JDBC插入“某些东西”?

2 个答案:

答案 0 :(得分:3)

这是PostgreSQL中与客户端驱动程序和ORM交互的严格转换问题的另一种变体,它们将所有不理解的内容发送为String。

您需要将setObjectTypes.OTHER,IIRC一起使用。

    ps.setObject(2, foos.get(i).getName(), Types.OTHER);

PgJDBC应该作为unknown类型的绑定参数发送。因为你直接与PgJDBC合作,所以很容易让你处理,幸运的是;当人们使用ORM图层时,这真的很痛苦。

请参阅:

为背景。

答案 1 :(得分:2)

为什么不创建存储过程并使用String param从CallableStatement调用它来通过它插入带有ltree的行,如果preparedStatemnt.setString()不起作用?

其他解决方案可能是ps.setObject(2, foos.get(i).getPath(), Types.OTHER);,但我现在无法检查。

相关问题