简体   繁体   中英

JPA setting UUID as query parameter

I am getting issues in executing delete query using JPA .

The problem is that I am deleting a row based on UUID.

To accomplish delete task, I set the UUID parameter in JPA query setParameter method. But this fails giving CAST issues.

So I used the following:

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

But again it gave exception.

Here is the code--

Entity Class:

@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;

Manager Class:

@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;
    }
}

Exception Log:

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

UPDATE:

These are the dependencies in my 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>

Using super.removeById is the working solution-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM