如何在jdbc模板中使用uuid?

tzxcd3kk  于 2021-07-09  发布在  Java
关注(0)|答案(3)|浏览(450)

我使用spring框架和jdbc模板,还使用postgres。
我在postgres中有使用uuid作为主键的表,该列的类型是postgres的本地uuid。如何将这些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.

有什么想法吗?我快疯了。

sulc1iza

sulc1iza1#

尝试在查询中使用以下类型:

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
46qrfjad

46qrfjad2#

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

vmjh9lq9

vmjh9lq93#

您可以尝试使用prepared语句,并让db使用函数uuid\u generate\u v1()处理uuid创建
要使用此函数,首先需要在postgres数据库中运行以下命令来创建扩展:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

在你的刀里你可以:

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,因为db将使用函数uuid_generate_v1()为您执行此操作;

相关问题