S
S
sanek_gyy2019-03-08 23:42:52
PostgreSQL
sanek_gyy, 2019-03-08 23:42:52

How to save a Java object with a field of type Enum?

There is a cats table. The color column is of type Enum cats_color.
5c82d2c2b0da1430031149.png
There is a Cat class

@Entity
@Table(name = "cats")
public class Cat {

    @Id
    @NotNull
    private String name;

    @Column(name = "color")
    CatColor color;

    @NotNull(message = "Возраст кота должен Zбыть")
    @Column(name = "tail_length")
    private int tailLength;

    @Column(name = "whiskers_length")
    private int whiskersLength;
    public Cat() {
    }

    public Cat(@NotNull String name, CatColor color, @NotNull(message = "Возраст кота должен Zбыть") int tailLength, int whiskersLength) {
        this.name = name;
        this.color = color;
        this.tailLength = tailLength;
        this.whiskersLength = whiskersLength;
    }

and Enum
public enum CatColor {
    BLACK,
    WHITE;

    CatColor() {
    }
}

Make a request via postman
{
"name" : "qwertyq3",
"color" : "BLACK",
"tailLength": "33",
"whiskersLength": "31"
}
5c82d365b3c20752919922.png
I also tried with @Enumerated(EnumType.STRING) annotation. The same error only with the String type.
How to save in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2019-03-08
Hasanly @azerphoenix

Here is my example:

public class User {
@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"))
    @Enumerated(EnumType.STRING)
    private Set<Role> roles;
}

public enum Role {
    AUTHOR,
    CUSTOMER,
    ADMIN
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question