Fetching UUID with NamedNativeQuery: [B cannot be cast to java.util.UUID

Viewed 580

I have a special Hibernate query which I had to write as NamedNativeQuery. This looks like this:

@Entity
@Table(name = "XYZ")
@NoArgsConstructor
@AllArgsConstructor
@NamedNativeQueries({
    @NamedNativeQuery(
        name = [...],
        query = " SELECT DISTINCT uuid [...]" 
    )
})
public class XyzEntity implements Serializable {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Type(type = "uuid-binary")
    @Column(name = "uuid", columnDefinition = "RAW(32)", nullable = false)
    private UUID uuid;
}

The query itself works. The result set is accessed in this way:

public List<UUID> getXyz() {
    final Query query = getEntityManager().createNamedQuery([...]);
    final List<UUID> resultList = query.getResultList();
    return resultList;
}

But now, if I try to iterate over this result list, I get Caused by: java.lang.ClassCastException: [B cannot be cast to java.util.UUID

The invocation looks like this:

public void abc() {
    final List<UUID> uuids = service.getXyz();
   
    //the start of the loop causes java.lang.ClassCastException: [B cannot be cast to java.util.UUID
    for (UUID uuid : uuids) {
        //do something
    }
}

Obviously Hibernate cannot map the NamedNativeQuery result to a Java UUID properly because the content seems to be just binary. What's the proper way to handle this?

0 Answers
Related