提问者:小点点

在JDBC中Java类型到Postgres 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');

没有什么奇怪的。现在我想使用准备状态来批量处理:

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个答案

匿名用户

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

您需要将setObjectType. O其他一起使用,IIRC。

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

PgJDBC应该将其作为未知类型的绑定参数发送。因为您直接使用PgJDBC,幸运的是,这对您来说很容易处理;当人们使用ORM层时,这是一个真正的痛苦。

见:

  • macaddr/Inet类型的postgres在滑头
  • 将postgreSQLJSON列映射到Hibernate值类型
  • http://www.postgresql.org/message-id/CACTajFZ8hg_kom6QiVBa94Kx9L3XUqZ99RdUsHBFkSb1MoCPQ@mail.gmail.com

作为背景。

匿名用户

为什么不创建存储过程,并调用它从Callable语句与字符串参数插入行与ltree通过它,如果准备Statemnt. setString()不工作?

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