Spring Data JPA 在 Spring Boot 应用程序中不使用 AttributeConverter [英] Spring Data JPA not using AttributeConverter in Spring Boot Application

查看:35
本文介绍了Spring Data JPA 在 Spring Boot 应用程序中不使用 AttributeConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我有以下实体:

@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 类:

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

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

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

推荐答案

Drop the @Enumerated(EnumType.STRING):

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

这篇关于Spring Data JPA 在 Spring Boot 应用程序中不使用 AttributeConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆