简体   繁体   中英

How to add enum field in postgres?

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

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM