2017-08-11 26 views
0

我試圖通過彈簧數據的JPA使用@Convert,但我得到一個錯誤,這是我的代碼:將Java bean的列表<Long>到MySQL的JSON在Spring數據JPA

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 

那麼,什麼是錯的?

+0

也許[this](https://vladmihalcea.com/2017/08/08/how-to-store-schema-less-eav-entity-attribute-value-data-using-json-and-hibernate/ )後將是有用的.. – Cepr0

回答

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

改變列表收集到Array.By這種方式,正常工作!

相關問題