Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java enum and postgresql enum

CREATE TABLE customers
(
  first_name character varying(15),
  second_name character varying(20),
  login character varying(15) NOT NULL,
  password character varying(15),
  email character varying(40),
  gender gender,
  register_date date,
  date_of_birth date,
  address character varying(40),
  address_number integer,
  town character varying(20),
  CONSTRAINT login PRIMARY KEY (login)
)

I have this table and I created an enum of gender such as:

CREATE TYPE gender AS ENUM ( 'F', 'M',);

I am trying to insert into customers data from eclipse java with PreparedStatement but there is an error such as ERROR: column "gender" is of type gender but expression is of type character varying Hint: You will need to rewrite or cast the expression.

My Java code looks like:

PreparedStatement pre_state;

public enum gendertype {
    F,
    M;
}

pre_state = conn.prepareStatement("INSERT INTO"
            + " customers VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
pre_state.set(6, gendertype.F.toString());
like image 295
user2317288 Avatar asked May 10 '13 23:05

user2317288


2 Answers

I can take no credit for this answer as you have already solved it, but I will explain why it works.

PostgreSQL provides the answer when it says

Hint: You will need to rewrite or cast the expression

The Java code is creating a string literal value that represents the Java enum gendertype type.

Casting a literal to a PostgreSQL gender type is done by adding a casting suffix to the value ::gender.

So valid input would be

'F'::gender

or

'M'::gender

This works because all PostgreSQL types have a input method that takes a text representation and converts that to the internal form.

like image 58
Tim Child Avatar answered Sep 19 '22 23:09

Tim Child


Your solution would have been

pre_state.setObject(6, gendertype.F.toString(), Types.OTHER);
like image 27
abbas Avatar answered Sep 20 '22 23:09

abbas