0

In my model there is an enum field, trying to add an enum field to the database, but does not work, can you comment?

public class ChatMessage {
private MessageType messageType;
private String content;
private String sender;
public enum MessageType {
 CHAT,
 JOIN,
 LEAVE
}

my postgre code

CREATE TYPE messageType AS ENUM ('CHAT', 'JOIN', 'LEAVE');
CREATE TABLE "chatMessage" (
id SERIAL UNIQUE PRIMARY KEY,
messageType messageType,
content VARCHAR(255) NOT NULL,
sender VARCHAR(255) NOT NULL
);

I suppose that I incorrectly declare the variable enum in postgres

asked Mar 14, 2019 at 12:33

2 Answers 2

1

Use Enumerated Annotation and Spring will handle this for you. But in general Enums will be VARCHAR(X) in Postgres (see second link)

public class ChatMessage {
 @Enumerated(EnumType.STRING)
 private MessageType messageType;
 private String content;
 private String sender;
}

http://tomee.apache.org/examples-trunk/jpa-enumerated/

https://vladmihalcea.com/the-best-way-to-map-an-enum-type-with-jpa-and-hibernate/

answered Mar 14, 2019 at 12:39
Sign up to request clarification or add additional context in comments.

3 Comments

CREATE TYPE messageType AS ENUM ('CHAT', 'JOIN', 'LEAVE'); do not use?
You can try this. But you need to check if Spring JPA is fine with this. It is possible that @Enumerated(EnumType.STRING) is also triggering creating an enum type. I would jpa create your database.
If your Enum will be extended in your Java Entity it could be necessary to edit your postgres enum type as well. Let JPA manage it...
0

If I get it right, according to the documentation your doing fine.

Although in their example they choose a different name for the column that references the Enum Type. Try change it, like, messages messageType.

Another example: https://tapoueh.org/blog/2018/05/postgresql-data-types-enum/#postgresql-enum-data-type

answered Mar 14, 2019 at 12:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.