5

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.

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
BHarman
  • 572
  • 1
  • 6
  • 15

1 Answers1

19

Drop the @Enumerated(EnumType.STRING):

// @Enumerated(EnumType.STRING)
@Column(name = "type")
@Convert(converter = CustomerLeadTypeConverter.class)
private CustomerLeadType type = CustomerLeadType.OPEN;
Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
  • 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? – Arun Gowda Aug 16 '21 at 13:22
  • 3
    @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. – nasch Jan 27 '22 at 20:46