AWS DynamoDB:无法取消转换属性错误

D.Z*_*Zet 4 java json amazon-web-services amazon-dynamodb objectmapper

我有一个问题,无法解决。我已经在KitchenService中创建了CRUD方法。我有addProduct等方法,这些方法都可以正常工作。.但是我在使用Product类字段的地方有Recipe类。

我的addRecipe方法:

public Recipe addRecipe (Recipe recipe){

    List<RecipeElement> recipeElements = recipe.getRecipeElements();
    for (RecipeElement recipeElement : recipeElements) {
        String id = recipeElement.getProduct().getId();
        Product product = databaseController.get(Product.class, id);
        recipeElement.setProduct(product);
    }

    databaseController.saveRecipe(recipe);
    logger.log("Recipe created");

    return recipe;
Run Code Online (Sandbox Code Playgroud)

构建成功,所以我想在POSTMAN中对其进行测试,这就是我发送的JSON Witch的外观:

{"id":null,"name":"test3","labels":["GLUTEN_FREE"],"author":{"name":"Plejer Anno?n","id":"testID2"},"media":{"name":"heheszki","url":"http://blabla.pl","mediaType":"IMAGE"},"recipeElements":[{"product":{"id":"ecacaf36-29a2-41c6-942e-be5a715ed094"},"weight":"100"}],"approved":false}
Run Code Online (Sandbox Code Playgroud)

然后我得到“消息”:“内部服务器错误”,所以我正在检查日志,这就是我在这里发现的内容:

Product[Media]; could not unconvert attribute: com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException

Caused by: com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: could not invoke public void pl.javamill.model.kitchen.Product.setMedia(pl.javamill.model.common.Media) on class pl.kitchen.Product with value {name=heheszki, url=http://blabla.pl, mediaType=IMAGE} of type class java.util.LinkedHashMap
Run Code Online (Sandbox Code Playgroud)

这是食谱类的外观:

@DynamoDBTable(tableName = "recipe")
public class Recipe extends Request {
/**
 * Id of kitchen content
 */
private String id;
/**
 * Name of recipe
 */
private String name;

/**
 * Labels of product for example gluten fee product
 */
private List<KitchenLabel> labels;

/**
 * Author of content.
 */
private Author author;

/**
 * Address of content image.
 */
private Media media;

private Boolean approved;

private List<RecipeElement> recipeElements;

@DynamoDBHashKey(attributeName = "id")
@DynamoDBAutoGeneratedKey
public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

@DynamoDBAttribute(attributeName = "Name")
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@DynamoDBTypeConverted(converter = EnumConverter.class)
@DynamoDBAttribute(attributeName = "Labels")
public List<KitchenLabel> getLabels() {
    return labels;
}

public void setLabels(List<KitchenLabel> labels) {
    this.labels = labels;
}

@DynamoDBTypeConverted(converter = ObjectConverter.class)
@DynamoDBAttribute(attributeName = "Author")
public Author getAuthor() {
    return author;
}

public void setAuthor(Author author) {
    this.author = author;
}

@DynamoDBTypeConverted(converter = ObjectConverter.class)
@DynamoDBAttribute(attributeName = "Media")
public Media getMedia() {
    return media;
}

public void setMedia(Media media) {
    this.media = media;
}

@DynamoDBAttribute(attributeName = "Approved")
public Boolean getApproved() {
    return approved;
}

public void setApproved(Boolean approved) {
    this.approved = approved;
}

@DynamoDBTypeConverted(converter = ObjectConverter.class)
@DynamoDBAttribute(attributeName = "RecipeElements")
public List<RecipeElement> getRecipeElements() {
    return recipeElements;
}

public void setRecipeElements(List<RecipeElement> recipeElements) {
    this.recipeElements = recipeElements;
}
Run Code Online (Sandbox Code Playgroud)

RecipeElement类:

public class RecipeElement {


private Product product;
private Integer weight;

@DynamoDBTypeConverted(converter = ObjectConverter.class)
@DynamoDBHashKey(attributeName = "product")
public Product getProduct() {
    return product;
}

public void setProduct(Product product) {
        this.product = product;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }
}
Run Code Online (Sandbox Code Playgroud)

和产品类别:

@DynamoDBTable(tableName = "product")
public class Product extends Request {
    /**
     * Id of kitchen content
     */
    private String id;

    /**
     * Name of product
     */
    private String name;

    /**
     * Calories in 100g
     */
    private Integer calories;

    /**
     * Fat in 100g
     */
    private Double fat;

    /**
     * Total carbo in 100g
     */
    private Double carbo;

    /**
     * Total Protein in 100g
     */
    private Double protein;

    /**
     * Labels of product for example gluten fee product
     */
    private List<ProductKind> productKinds;

    /**
     * Author of content.
     */
    private Author author;

    /**
     * Address of content image.
     */
    private Media media;

    private Boolean approved;

    @DynamoDBHashKey(attributeName = "id")
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @DynamoDBAttribute(attributeName = "Name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @DynamoDBAttribute(attributeName = "Calories")
    public Integer getCalories() {
        return calories;
    }

    public void setCalories(Integer calories) {
        this.calories = calories;
    }

    @DynamoDBAttribute(attributeName = "Fat")
    public Double getFat() {
        return fat;
    }

    public void setFat(Double fat) {
        this.fat = fat;
    }

    @DynamoDBAttribute(attributeName = "Carbo")
    public Double getCarbo() {
        return carbo;
    }

    public void setCarbo(Double carbo) {
        this.carbo = carbo;
    }

    @DynamoDBAttribute(attributeName = "Protein")
    public Double getProtein() {
        return protein;
    }

    public void setProtein(Double protein) {
        this.protein = protein;
    }

    @DynamoDBTypeConverted(converter = EnumConverter.class)
    @DynamoDBAttribute(attributeName = "ProductKinds")
    public List<ProductKind> getProductKinds() {
        return productKinds;
    }

    public void setProductKinds(List<ProductKind> productKinds) {
        this.productKinds = productKinds;
    }

    @DynamoDBTypeConverted(converter = ObjectConverter.class)
    @DynamoDBAttribute(attributeName = "Author")
    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }

    @DynamoDBTypeConverted(converter = ObjectConverter.class)
    @DynamoDBAttribute(attributeName = "Media")
    public Media getMedia() {
        return media;
    }

    public void setMedia(Media media) {
        this.media = media;
    }

    @DynamoDBAttribute(attributeName = "Approved")
    public Boolean getApproved() {
        return approved;
    }

    public void setApproved(Boolean approved) {
        this.approved = approved;
    }
Run Code Online (Sandbox Code Playgroud)

这是我的转换器类:

public class ObjectConverter<T extends Object> 
implements DynamoDBTypeConverter<String, T> {

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convert(T object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        throw new IllegalArgumentException("Unable to parse JSON");
    }

    @Override
    public T unconvert(String object) {
        try {
            T unconvertedObject = objectMapper.readValue(object, 
                new TypeReference<T>() {
            });
            return unconvertedObject;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?

小智 5

简短答案

Media类添加一个公共的空构造函数。

长答案

在你的代码,当你执行databaseController.get(Product.class, id),你调用的方法下划线public T unconvert(final Map<String,AttributeValue> object)DynamoDBMapperTableModel

@Override
public T unconvert(final Map<String,AttributeValue> object) {
    final T result = StandardBeanProperties.DeclaringReflect.<T>newInstance(targetType);
    if (!object.isEmpty()) {
        for (final DynamoDBMapperFieldModel<T,Object> field : fields()) {
            try {
                final AttributeValue value = object.get(field.name());
                if (value != null) {
                    field.unconvertAndSet(result, value);
                }
            } catch (final RuntimeException e) {
                throw new DynamoDBMappingException(
                    targetType.getSimpleName() + "[" + field.name() + "]; could not unconvert attribute", e
                );
            }
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

在此方法的第一行中,将使用反射创建表模型的新实例(在您的情况下为的新实例Product),然后将新实例的字段转换为所需的类并进行相应的设置。

StandardBeanProperties.DeclaringReflect.<T>newInstance(targetType)调用 .newInstance()targetType,巫婆它的类型是Class<T>

Class.newInstance()文档中所述InstantiationException如果该类没有null构造函数,则抛出该异常。在其他情况下,将引发此异常,但是根据我的经验,这可能是因为未实现公共空构造函数。