gpt4 book ai didi

spring - 使用 @Converter 为泛型类实现 AttributeConverter

转载 作者:行者123 更新时间:2023-12-02 08:26:11 25 4
gpt4 key购买 nike

如何实现泛型的 AttributeConverter?

类似的东西

class JSONConverter<T> implements AtttributeConverter<T,String>{
//Here How do I get the generic class type with which I can convert a serialized object
}

在实体类中调用转换器

@Column
@Convert( converter = JSONConverter.class) //How do I pass the Generic here
private SomeClass sm;

最佳答案

可以做得更简单,因为您不一定需要通过构造函数传递 typeReference:

public abstract class JsonConverter<T> implements AttributeConverter<T, String> {

private final TypeReference<T> typeReference = new TypeReference<T>() {};

@Resource
private ObjectMapper objectMapper;

@Override
public String convertToDatabaseColumn(T object) {
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}

@Override
public T convertToEntityAttribute(String json) {
try {
return objectMapper.readValue(json, typeReference);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}

然后是类,扩展你的 JsonConventer 看起来像:

public class SomeClassConverter extends JsonConverter<SomeClass> { }

关于spring - 使用 @Converter 为泛型类实现 AttributeConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42413204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com