转换列表< Long> Spring数据JPA中将Java bean转换为mysql的json [英] Convert the List<Long> of java bean to the json of mysql in Spring data JPA

查看:247
本文介绍了转换列表< Long> Spring数据JPA中将Java bean转换为mysql的json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have tried to use @Convert by spring-data-jpa, but I get an error, this is my code:

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

那怎么了?

推荐答案

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

At last, i solved this problem. I change my code like this:

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

将列表集合更改为数组,这样可以正常工作!

Change the List Collection to a Array.By this way, it work normally!

这篇关于转换列表&lt; Long&gt; Spring数据JPA中将Java bean转换为mysql的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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