如何检查 JPQL 中的 UUID 空值?

How to check UUID null value in JPQL?

我正在使用 JPA/Hibernate。所以我想在 JPQL 中做 nullCheck,但是当我这样做时它不能确定数据类型。

JPQL 查询:

  @Query("select a from Attribute a where :attributeId is null OR a.id = :attributeId")
  Page<Attribute> findByAttributeId(@Param("attributeId") UUUID attributeId);

异常:

Caused by: org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2532) at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2267) at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:312) at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:448) at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:369) at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:153) at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:103) at jdk.internal.reflect.GeneratedMethodAccessor582.invoke(Unknown Source) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114) at com.sun.proxy.$Proxy398.executeQuery(Unknown Source) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60) ... 114 common frames omitted

我在互联网上搜索了很多关于这个主题的内容,但找不到解决方案。 我不想在服务层处理它。

我试过了:

  1. PostgreSql CAST 函数
  2. 检查为字符串
  3. @类型注释。

在 JPQL 中是否有检查 UUID 空值的方法?

我在使用 JPA 3.0 + EclipseLink + PostgreSQL 时遇到了类似的错误,这是由于参数自动转换引起的。尝试将 stringtype=unspecified 添加到您的连接 URL: jdbc:postgresql://SERVER:5432/mydatabase?stringtype=unspecified

在网上查了一下后,我找到了解决办法。 由于 PostgreSQL 无法确定数据类型,我们可以从之前声明为 TypedParameterValue。

TypedParameterValue attributeId = new TypedParameterValue(PostgresUUIDType.INSTANCE, UUIDUtil.toUUID(attributeId));
Page<Attribute> attributes = attributeRepo.findByAttributeId(attributeId);

然后在 JPQL 中进行 nullChecking,转换为 org.hibernate.type.PostgresUUIDType:
(在IDE中可以显示错误,但实际编译通过)

 @Query("select a from Attribute a where (cast(:attributeId as org.hibernate.type.PostgresUUIDType) OR a.id = :attributeId)")
 Page<Attribute> findByAttributeId(@Param("attributeId") TypedParameterValue attributeId);

在本机查询中:

 @Query(value = "select * from attribute a where (cast(:attributeId as uuid) OR a.id = :attributeId)",nativeQuery = true)
 List<Attribute> findByAttributeId(@Param("attributeId") TypedParameterValue attributeId);