'org.postgresql.util.PGobject cannot be cast to java.lang.String

trying to learn how to use PostgeSQL data base, and JAVA with ENUM's and got some problem with casting.

Here is my sql:

CREATE TYPE enum_created_from AS ENUM ('CHAT', 'WEB');
ALTER TABLE contact ADD COLUMN created_from enum_created_from;
UPDATE contact SET created_from='WEB';

Enum file:

public enum ContactCreatedFrom {
    WEB, CHAT;
}

JAVA Entity file:

@Column(name = "CREATED_FROM")
@Enumerated(EnumType.STRING)
private ContactCreatedFrom createdFrom;

off course getters and setters.

@Test file using JUnit

@Test
public void testContactCreatedFrom() 
{
    try
    {
        @SuppressWarnings("unchecked")
        List<Contact> contacts = (List<Contact>) db.createQuery("from Contact where id between 20 and 25").list();
        for (Contact c : contacts)
        {
            System.out.println("Name: " + c.getName());
            System.out.println ("Enum: " + c.getCreatedFrom());
        }
    } catch (Exception e)
    {
        System.out.println("Exception: " + e);
    }
}

And I still getting Exception:

Exception: java.lang.ClassCastException: org.postgresql.util.PGobject cannot be cast to java.lang.String

Can anybody tell me where I'm wrong please.

Regards



Solution 1:[1]

I got an explanation from the Postgres documentation here: https://jdbc.postgresql.org/documentation/publicapi/org/postgresql/util/PGobject.html . I then cast the PGObject as PGObject, then used object.getValue() for its String value. That seemed to sort my issue. Example:

import org.postgresql.util.PGobject;

public static String pgObjectToString(PGobject object){
        if(null==object) return null;
        String s = object.getValue();
        return s;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kennedy Buluma