3

I have column 'gender' as a VARCHAR(1)/CHAR. How to parse values "M"/"F" to java enum with values (MALE, FEMALE) in @Entity class without using

@Column(name="gender")
private Character cGender;

and converting it manually to enum object?

Vadym Borys
  • 115
  • 2
  • 11

3 Answers3

3

You need to provide your own converter:

@Convert(converter = GenderConverter.class)
@Column(name="gender")
private Gender gender;

Then implement it

public class GenderConverter implements AttributeConverter<Gender, Character> {
    @Override
    public Character convertToDatabaseColumn(Gender from) {

        Character value = 'm';

        if (from == Gender.FEMALE) {
            value = 'f';
        }

        return value;
    }

    @Override
    public Gender convertToEntityAttribute(Character to) {
        Gender g = Gender.MALE;
        if ('f' == to)
            g = Gender.FEMALE;
        }
        return g;
    }
}
Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40
  • yes, You're right, the way I propose will only record the enum and not the value. – Dilnei Cunha Jun 14 '17 at 18:08
  • 1
    Also it's possible to add @Converter(autoApply = true) on coverter class and after that Hibernate will be converting all Gender fields automatically (no need for @Convert(converter = GenderConverter.class)). – Mykola Yashchenko Jun 15 '17 at 15:11
  • @NikolayYashchenko interesting! I think you should post this as an alternative answer, since I wasn't familiar with that – Alexey Soshin Jun 15 '17 at 19:55
  • 1
    See similar problem/solution: https://stackoverflow.com/questions/2751733/map-enum-in-jpa-with-fixed-values#25246982 – Curtis Yallop Feb 21 '19 at 20:51
0

For enum you can use enum type instead to use Character type, eg:

@Enumerated(EnumType.STRING)
@Column(name = "GENDER")
private Gender gender; 
Dilnei Cunha
  • 159
  • 4
  • 10
  • Then i'll get an exception: Unknown name value [M] for enum class [network.models.Gender]. Because column value is not a full name of enum, this is just 1 char M/F. – Vadym Borys Jun 14 '17 at 19:20
  • yes, you should use as @Alexey Soshin wrote providing your own converter. – Dilnei Cunha Jun 14 '17 at 19:43
0

In addition to the answer of @Alexey Soshin: Also it's possible to add @Converter(autoApply = true) on coverter class and after that Hibernate will be converting all Gender fields automatically (no need for @Convert(converter = GenderConverter.class)).

Mykola Yashchenko
  • 5,103
  • 3
  • 39
  • 48