如何在JDBC模板中使用UUID?

3
我正在使用Spring框架和JDBC模板,并且还在使用Postgres。
我在Postgres中有一些使用UUID作为主键的表,该列的类型为Postgres的native UUIDs。如何将这些UUID存储在通过JDBC模板创建的预处理语句中?
我尝试将UUID转换为字符串,如下所示:
int rowsAffected = this.jdbc.update(sql, new Object[] {
    baseMaterial.getId().toString().toLowerCase(),
    baseMaterial.getName(),
    baseMaterial.getDescription()
});

但是这会导致出现这个错误:
ERROR: column "id" is of type uuid but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.

如果我只是使用原始的UUID,像这样:
int rowsAffected = this.jdbc.update(sql, new Object[] {
    baseMaterial.getId(),
    baseMaterial.getName(),
    baseMaterial.getDescription()
});

然后我最终遇到了这个错误:
org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of java.util.UUID. Use setObject() with an explicit Types value to specify the type to use.

任何想法吗?这让我发疯了。

你使用的是哪个版本的PostgreSQL JDBC驱动程序? - Mark Rotteveel
@MarkRotteveel <version>9.1-901-1.jdbc4</version> - Rico Kahler
1
我建议你升级到42.1.4版本,看看是否能解决你的问题。9.1-901已经过时6年了。 - Mark Rotteveel
@MarkRotteveel,果然,那解决了。将其作为答案发布,我会接受的。 - Rico Kahler
3个回答

4
您正在使用的PostgreSQL驱动程序版本已经有6年历史了,自那以后已经有很多变化/改进。我建议升级到版本42.1.4。
我已经扫描了发布说明,但我没有找到他们添加(或改进)UUID支持的具体版本。

2
尝试像这样在查询中使用类型:

尝试像这样在查询中使用类型:

int[] types = {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};

int rowsAffected = this.jdbc.update(sql, new Object[]{
    baseMaterial.getId().toString().toLowerCase(),
    baseMaterial.getName(),
    baseMaterial.getDescription()
}, types);//<<-----------specify the type of each attribute 

2

您可以尝试使用预处理语句,并让数据库使用uuid_generate_v1()函数来处理uuid的创建。

要使用此函数,您首先需要在Postgres数据库中运行以下命令以创建扩展:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

然后在您的DAO中,您可以执行以下操作:

private String ADD_USER = "insert into Users(id, name, description) values (uuid_generate_v1(), ?, ?)";
    
jdbcTemplate.update(ADD_USER, new PreparedStatementSetter() {
    @Override
    public void setValues(PreparedStatement preparedStatement) throws SQLException {
        preparedStatement.setString(1, name);
        preparedStatement.setString(2, description);
    }
});

您无需担心插入uuid,因为数据库将使用函数uuid_generate_v1()为您完成此操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接