【问题标题】:Convert the List<Long> of java bean to the json of mysql in Spring data JPASpring data JPA中将java bean的List<Long>转换为mysql的json
【发布时间】:2018-01-19 11:16:23
【问题描述】:

我曾尝试通过 spring-data-jpa 使用 @Convert,但出现错误,这是我的代码:

entity
@Convert(converter = ListExtendConverterJson.class)
private List<Long> receivers;

ListExtendConverterJson implements AttributeConverter<List<Long>, String>:

@Override
public String convertToDatabaseColumn(List<Long> list) {
    String result =  JSONArray.toJSONString(list);
    return result;
}

@Override
public List<Long> convertToEntityAttribute(String s) {
    List<Long> result = JSONArray.parseArray(s, Long.class);
    return result;
}

这是错误信息:

Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to java.util.List
at com.qf.posp.pub.config.entity.json.ListExtendConverterJson.convertToDatabaseColumn(ListExtendConverterJson.java:23)
at org.hibernate.type.descriptor.converter.AttributeConverterSqlTypeDescriptorAdapter$1.bind(AttributeConverterSqlTypeDescriptorAdapter.java:78)
... 78 common frames omitted

那么有什么问题呢?

【问题讨论】:

  • 也许this 的帖子会有用..

标签: mysql json spring-data-jpa type-conversion


【解决方案1】:

最后,我解决了这个问题。我像这样更改我的代码:

entity:
@Convert(converter = ListExtendConverterJson.class)
private Long[] receivers;

public class ListExtendConverterJson implements AttributeConverter<Long[], String> {

@Override
public String convertToDatabaseColumn(Long[] list) {
    String result =  JSONArray.toJSONString(list);
    return result;
}

@Override
public Long[] convertToEntityAttribute(String s) {
    List<Long> list = JSONArray.parseArray(s, Long.class);
    Long[] result = new Long[list == null ? 0 :list.size()];
    if(!CollectionUtils.isEmpty(list)) {
        int i = 0;
        for(Long l : list) {
            result[i] = l;
            i ++;
        }
    }
    return result;
}

将List Collection改为Array,这样就可以正常工作了!

【讨论】:

    猜你喜欢
    • 2015-09-09
    • 2019-07-31
    • 2019-12-03
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    相关资源
    最近更新 更多