skip to Main Content

I have enum in java

public enum Day {
    MONDAY("D1", "X"),
    TUESDAY("D2", "X"),
    WEDNESDAY("D3", "X"),
    THURSDAY("D4", "X"),
    FRIDAY("D5", "X"),
    SATURDAY("D6", "X"),
    SUNDAY("D7", "Y");

    private final String value;
    private final String value2;

    Day(String value, String value2) {
        this.value = value;
    this.value2 = value2
    }

    public String getvalue() {
        return value;
    }

    public String getvalue2() {
        return value2;
    }
}

in my hibernate entity I have

  @Column(name = "day", nullable = false, length = 50)
    @Enumerated(EnumType.STRING)
    private Day day; 

on postgres database it saves MONDAY but I want D1.
I tried EnumType.String but I need something else I guess

2

Answers


  1. You can implement an AttributeConverter class, then annotate your enum with

    @Convert(converter = DayConverter.class)
    

    Eg. (the second function needs some more work)

    @Converter(autoApply = true)
    public class DayConverter implements AttributeConverter<Day, String> {
    
        @Override
        public Integer convertToDatabaseColumn(Day day) {
            return day.getValue();
        }
    
        @Override
        public Day convertToEntityAttribute(String databaseValue) {
            return MONDAY;
        }
    }
    
    Login or Signup to reply.
  2. add these following methods to your Enum class.

    to get the enum from a value(eg. return MONDAY when you pass D1):

    public static Day fromValue(String value) {
        for (Day day : Day.values()) {
            if (day.getValue().equals(value)) {
                return day;
            }
        }
        // throw some exception
        return null; 
    }
    
    // input: "D1" -> output : MONDAY
    

    to get value when you pass Day(eg. return D1 when you pass Day.MONDAY):

    public static String toValue(Day day) {
        return day.getValue();
    }
    // input: Day.MONDAY -> output : "D1"
    

    NOTE: but it seems that you are trying to save Enum into your database column, so you should pass a day to your column.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search