Spring JPA不会将自定义值枚举类型保存到数据库

时间:2017-11-09 09:40:29

标签: java spring postgresql jpa enums

我有一个枚举定义如下,其中值应该是-2,-1,0,1,2:

public enum Rating {

    EXTREMELY_DISSATISIFIED(-2),
    DISSATISFIED(-1),
    NEUTRAL(0),
    SATISFIED(1),
    EXTREMELY_DISSATIFIED(2);

    private final int rating;

    Rating(int rating) {
        this.rating = rating;
    }

    public int getValue() {
        return rating;
    }
}

在我的模型中,我有一个名为rating的属性,如下所示:

@Entity
public class Feedback {
    @Column(nullable=false)
    private Rating rating;

    public Feedback() {}

    public Rating getRating() {
        return rating;
    }
    public void setRating(Rating rating) {
        this.rating = rating;
    }
}

然后,通过RESTful API,我使用以下代码保存评级:

@Service
public class FeedbackService {

    @Autowired
    private FeedbackRepository feedbackRepository;

    public Feedback addFeedback(Feedback feedback) {
        return feedbackRepository.save(feedback);
    }
}

所以,当我POST提出如下请求时:

{
   "rating": "EXTREMELY_DISSATISFIED"
}

我希望在POSTgres数据库中看到值-2。但是,我仍然看到0作为普通枚举将从0开始。如何调整数据库以将值存储为-2,-1,0,1和2?

2 个答案:

答案 0 :(得分:2)

您可以使用自定义转换器twitch和  @Convert annotation喜欢这样:

@Convert(converter = EnumToIntValue.class)
private Rating rating;

以这种方式编写EnumToIntValue转换器类:

public class EnumToIntValue implements AttributeConverter<Rating, Integer> {

    @Override
    public Integer convertToDatabaseColumn(final Rating rating) {
        return rating.getValue();
    }

    @Override
    public Rating convertToEntityAttribute(final int dbData) {
        if (dbData == -2) {
            return Rating.EXTREMELY_DISSATISIFIED;
        } else if (dbData == -1) {
            return Rating.DISSATISFIED;
        } else if (dbData == 0) {
            return Rating.NEUTRAL;
        } else if (dbData == 1) {
            return Rating.SATISFIED;
        }else if(dbData == 2){
            return Rating.EXTREMELY_SATIFIED;
        }else{
            return null
        }
    }
}

答案 1 :(得分:1)

您始终可以使用可以自定义存储值的AttributeConverterHERE是一个很好的教程。