4

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 ?

Olivier J.
  • 3,115
  • 11
  • 48
  • 71

1 Answers1

1

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.

Community
  • 1
  • 1
rbento
  • 9,919
  • 3
  • 61
  • 61
  • But you use varchar and not the user defined type. – Christoph Leiter Feb 13 '13 at 17:28
  • Yes, when using varchar in table it's work but I use enum type langage, not varchar. Thx anyway – Olivier J. Feb 13 '13 at 17:39
  • I see your point, but there are a couple things I could mention about it. If you have an enum type defined in database and a correspondent enum in Java, you may have duplicated knowledge. Not good for maintenance at all. By defining an enumerated field with EnumType.STRING and storing it's string representation you keep the knowledge in your application. Furthermore, JPA providers should be database agnostic, so Eclipselink allows you to save an enum value as either an ordinal or string. If you're wanting to save string, varchar is the way to go. Nothing wrong with that. – rbento Mar 09 '13 at 22:40