3

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

Robertas Uldukis
  • 801
  • 1
  • 11
  • 20
  • possible duplicate of [Java Enums, JPA and Postgres enums - How do I make them work together?](http://stackoverflow.com/questions/851758/java-enums-jpa-and-postgres-enums-how-do-i-make-them-work-together) – Scary Wombat May 07 '14 at 08:33
  • 1
    Sorry, but i think problem is not there. i already try it before posted this question. – Robertas Uldukis May 07 '14 at 11:26

1 Answers1

2

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;
}
  • I have used String.valueOf(map.get(KEY)) for jdbcTemplate.queryForList.It is working fine now – manish Feb 08 '23 at 04:14