我有一个spring boot应用程序,它为实体指定一个AttributeConverter,该实体将枚举从大写转换为标题,以存储在数据库中。

我有以下实体:

@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;
}


以及以下AttributeConverter类:

@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);
        }
    }
}


@Converter(autoApply = true)@Convert(converter = CustomerLeadTypeConverter.class)似乎都不会触发转换。

最佳答案

删除@Enumerated(EnumType.STRING)

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

07-28 03:19