我在 JPA 中有一个本机查询
String sql1 = """
SELECT tier_id, tier_list, vm.id AS model_id, option_list, price, sku, stock
FROM (
SELECT *
FROM ecommerce.tier_variations tv
WHERE tv.product_id = ?1 AND is_deleted = false
) AS tv
JOIN ecommerce.variation_models vm ON vm.tier_id = tv.id
""";
@Query(value = sql1, nativeQuery = true)
List<VariationProjection> findVariations(String productId);
option_list 的结果是 db 中[{"image": "image1", "option": "L"}, {"image": "image2", "option": "X"}]
我使用投影来绘制地图
public interface VariationProjection {
List<String> getTier_list();
List<Map<String, Object>> getOption_list();
}
List getTier_list() 可以工作,但是 List> getOption_list() 不行
原因
使用 Jackson 的解决方案
将 Jackson 依赖项添加到您的项目中:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
创建自定义转换器:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.List;
import java.util.Map;
@Converter
public class JsonToListMapConverter implements AttributeConverter<String, List<Map<String, Object>>> {
private static final ObjectMapper objectMapper = new ObjectMapper();
@Override
public List<Map<String, Object>> convertToEntityAttribute(String dbData) {
try {
return objectMapper.readValue(dbData, new TypeReference<List<Map<String, Object>>>() {});
} catch (Exception e) {
...
}
}
}
更新您的界面 VariationProjection:
@Convert(converter = JsonToListMapConverter.class)
private List<Map<String, Object>> getOption_list;
现在,JPA 在获取数据时将自动使用 option_list 字段的转换器。