Bourne
Bourne

Reputation: 1927

Mapping enum('YES', 'NO') column in Mysql to Boolean in hibernate

I have mapped a Table in Mysql to Java class using hibernate. One of the column in the table has type "enum('YES', 'NO')". I want to map this to a Boolean in the java class using hibernate annotation.

As per the documentation below
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/types.html#types-value-basic
('Y', 'N'), ('0', '1') and ('T', 'F') can be mapped to Boolean.
How do I map "enum('YES', 'NO') to Boolean?

Upvotes: 2

Views: 3283

Answers (3)

Michael Hegner
Michael Hegner

Reputation: 5823

It is older post, but maybe someone helps. I needed a conversion of String to Boolean and back.

I wrote a converter:

@Converter(autoApply = true)
public class BusinessEnvironmentConverter implements AttributeConverter<Boolean, String> {
    enum BusinessEnvironment { TEST, PRODUCTION }

    @Override
    public String convertToDatabaseColumn(final Boolean production) {
        return production ? BusinessEnvironment.PRODUCTION.name(): BusinessEnvironment.TEST.name();
    }

    @Override
    public Boolean convertToEntityAttribute(final String dbField) {
        final BusinessEnvironment businessEnvironment = BusinessEnvironment.valueOf(dbField);
        return businessEnvironment.equals(BusinessEnvironment.PRODUCTION) ? TRUE : FALSE;
    }
}

And using it:

@Column(name=PRODUCTION, nullable=false)
@Convert(
        converter=BusinessEnvironmentConverter.class,
        disableConversion=false
)
private boolean production;

Upvotes: 2

wds
wds

Reputation: 32283

Those types are all based on mapping a one CHAR column. I think it may be possible to map the enum to a java enum out of the box, but the only way to achieve what you want is likely to implement your own type, i.e. an implementation of UserType.

Upvotes: 0

Kerb
Kerb

Reputation: 1168

Not tested, not compiled:

public class SomeEntity {
    ....
    public enum YesNoEnumType {
        YES, NO
    }


    private YesNoEnumType someBooleanField;

    @Column(name = "SOME_BOOLEAN_FIELD)
    @Enumerated(YesNoEnumType.STRING)
    private YesNoEnumType getSomeBooleanField() {
        return this.someBooleanField;
    }
    ...

Upvotes: 1

Related Questions