Olivier J.
Olivier J.

Reputation: 3165

PostgreSQL, enum, JPA, EclipseLink

I wonder how to map with JPA Java enum and PostgreSQL enum type ?

In PostgreSQL side I have created this type :

CREATE TYPE langage AS ENUM ('FR', 'EN', 'DE');

And I have a Java enum :

public enum LangageEnum {   
   FR,
   EN,
   DE;
}

My JPA entity field is this one :

@Enumerated(EnumType.STRING)
@Column(name="langage")
private LangageEnum langage = LangageEnum.FR;

but I receive Exception :

Caused by: org.postgresql.util.PSQLException: ERREUR: la colonne « langage » est de type pretoria.langage mais l'expression est de type character varying Indice : Vous devez réécrire l'expression ou lui appliquer une transformation de type.

I think I can succeed using ObjectTypeConverter as show here

but ObjectTypeConverter is a EclipseLink annotation, not JPA so I'm looking for another way to do this.

So, how can I map Java enum to PostgreSQL enum please ?

Upvotes: 4

Views: 2034

Answers (1)

rbento
rbento

Reputation: 11608

It seems that you've created an enum type in Postgres, but what about the field in a table?

This works for me:

Enum

public enum CampaignState
{
    READY,
    RUNNING,
    PAUSED,
    FINISHED;
}

Entity

...
@NotNull
@Enumerated(EnumType.STRING)
private CampaignState state = CampaignState.READY;
...

Table

CREATE TABLE campaign
(
    id UUID PRIMARY KEY,
    ...
    state CHARACTER VARYING(64) NOT NULL, -- defined by application
    ...
);

I hope it helps.

>> Edit

As per your comment, please, take a look at this answer.

Upvotes: 1

Related Questions