JPA将UUID设置为查询参数

时间:2018-01-06 16:28:12

标签: java hibernate jpa

我在使用delete query执行JPA时遇到问题。

问题是我正在删除基于UUID的行。

要完成删除任务,我在JPA查询UUID方法中设置了setParameter参数。但这无法给出CAST个问题。

所以我使用了以下内容:

query.setParameter("fileUuid", String.class.cast(fileUuid));

但它又一次例外。

这是代码 -

实体类:

@Id
@Type(type = "pg-uuid")
@GenericGenerator(name = "uuid-gen", strategy = "uuid2")
@GeneratedValue(generator = "uuid-gen")
@Column(name = "file_uuid", updatable = false, nullable = false)
private UUID fileUuid;

经理班级:

@Override
public void deleteFile(UUID fileUuid) {
    final String ql = "delete from " + type.getName() + "  
    where file_uuid = :fileUuid";
    Query query = getEntityManager().createQuery(ql);
    query.setParameter("fileUuid", 
    String.class.cast(fileUuid));
    try {
        query.executeUpdate();
    } catch (NoResultException ex) {
        return;
    }
}

异常日志:

java.lang.ClassCastException: Cannot cast java.util.UUID to java.lang.String
        at java.lang.Class.cast(Class.java:3369)

更新:

这些是我的pom.xml中的依赖项 -

    <dependency>
      <groupId>org.hibernate.javax.persistence</groupId>
      <artifactId>hibernate-jpa-2.1-api</artifactId>
       <version>1.0.0.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
       <version>4.3.11.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.3.11.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-ehcache</artifactId>
      <version>4.3.11.Final</version>
    </dependency>

1 个答案:

答案 0 :(得分:0)

使用super.removeById是可行的解决方案 -

@Override
public void deleteFile(UUID fileUuid) {
    T entity =getEntityManager().find(type, id)
    if (entity != null) {
      getEntityManager().remove(entity);
    }        
}