8

I have a spring boot application that designates an AttributeConverter for an entity that converts an enum from uppercase to title case for storage in the database.

I have the following entity:

@Entity
@Table(name = "customerleads")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class CustomerLead implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(name = "type")
    @Convert(converter = CustomerLeadTypeConverter.class)
    private CustomerLeadType type = CustomerLeadType.OPEN;
}

And the following AttributeConverter class:

@Converter(autoApply = true)
public class CustomerLeadTypeConverter implements AttributeConverter<CustomerLeadType, String> {

    @Override
    public String convertToDatabaseColumn(CustomerLeadType attribute) {
        switch (attribute) {
            case OPEN:
                return "Open";
            case CLOSED:
                return "Closed";
            case DELETED:
                return "Deleted";
            default:
                throw new IllegalArgumentException("Unknown" + attribute);
        }
    }

    @Override
    public CustomerLeadType convertToEntityAttribute(String dbData) {
        switch (dbData) {
            case "Open":
                return OPEN;
            case "Closed":
                return CLOSED;
            case "Deleted":
                return DELETED;
            default:
                throw new IllegalArgumentException("Unknown" + dbData);
        }
    }
}

Neither @Converter(autoApply = true) nor the @Convert(converter = CustomerLeadTypeConverter.class) seem to trigger the conversion.

1 Answer 1

23

Drop the @Enumerated(EnumType.STRING):

// @Enumerated(EnumType.STRING)
@Column(name = "type")
@Convert(converter = CustomerLeadTypeConverter.class)
private CustomerLeadType type = CustomerLeadType.OPEN;
Sign up to request clarification or add additional context in comments.

2 Comments

Just curious. Can we not use any annotations on custom converted types? like @Lob? I see @Column though. What type of annotations are not allowed?
@ArunGowda If I understand correctly, the problem is '@Enumerated' and '@Convert' are in conflict. They're instructing to use two mutually exclusive methods to convert between an enum and another value type. That's why you can't use both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.