【问题标题】:Hibernate named query with UUID as parameter以 UUID 作为参数的 Hibernate 命名查询
【发布时间】:2015-04-14 02:22:37
【问题描述】:

我正在尝试对 Postgres 数据库使用命名查询来选择具有给定 UUID(用作外键)的所有行。这是正在调用的命名查询。

  @NamedNativeQuery(name = "getAllXByFK",
  query = "SELECT * FROM table n WHERE FK = :param",
    resultClass = Foobar.class)})

我使用 java.util.UUID 类型设置参数。

query.setParameter(param.getKey(), param.getValue());

当我用query.list()去获取ResultSet时,报如下错误:

错误:运算符不存在:uuid = bytea

有什么建议吗?

【问题讨论】:

标签: java hibernate uuid


【解决方案1】:

不是很漂亮,但这对我有用:

SQL:

SQLQuery query = session.createSQLQuery("... where cast(c.id as varchar) = :id ");

参数设置如下:

query.setString("id", myUUID.toString());

我只是想知道如果对列执行强制转换,PostgreSQL 是否仍然使用id 上的索引...?

编辑:

使用 Hibernate 5.0.9,奇怪的是我不需要丑陋的演员表,我可以按预期设置参数:

query.setParameter("id", myUUID);

编辑 2019-05-11:

对于 SQL 查询,我现在倾向于在我的 Hibernate 项目中使用 jdbcTemplate。只需自动装配并使用它:

@Autowired
private NamedParameterJdbcTemplate  jdbcTemplate;

// ...

MapSqlParameterSource p = new MapSqlParameterSource("name", "value");
p.addValue("anotherParam", true);
List<Map<String, Object>> result = jdbcTemplate.queryForList("select ... where id = :name", p);

【讨论】:

  • 它不使用索引。没有强制转换,当解释给出Index Scan... 之后转换解释给出Seq Scan...
【解决方案2】:

当您为绑定参数提供null 值时,通常会报告此错误。

【讨论】:

    猜你喜欢
    • 2011-06-07
    • 2017-04-13
    • 2010-10-08
    • 2011-01-27
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多