我对嵌套类的thymeleaf表单有问题。我正在做卡路里计数器的应用程序,当我试图添加一个新的食品产品到现有的一餐我得到一个例外。foodproduct是一个类,它处理所有foodproduct的模板,例如apple、chicken breast等。
食品类:
@Entity
@Table(name = "food_products")
public class FoodProduct {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "product_name")
private String productName;
@Column(name = "proteins")
private Double proteins;
@Column(name = "fats")
private Double fats;
@Column(name = "carbohydrates")
private Double carbohydrates;
@Column(name = "calories")
private Double calories;
// ...
}
mealfoodproduct类别:
@Entity
@Table(name = "meals_food_products")
@IdClass(MealFoodProductPK.class)
public class MealFoodProduct {
@Id
@ManyToOne
@JoinColumn(name = "meal_id")
private Meal meal;
@Id
@ManyToOne
@JoinColumn(name = "food_product_id")
private FoodProduct foodProduct;
@Column(name = "food_product_weight")
private double weight;
//...
}
html表单:
<form action="#" th:action="@{/saveMealFoodProduct}" th:object="${mealFoodProduct}" method="post">
<div>
<label>Product name</label>
<div>
<select th:field="*{foodProduct}">
<option th:each="foodProduct : ${foodProducts}" th:text="${foodProduct}" th:value="${foodProduct.id}"></option>
</select>
</div>
</div>
<div>
<label>Weight</label>
<div>
<input type="number" th:field="*{weight}" placeholder="Enter weight">
</div>
</div>
<br>
<div>
<div>
<button type="submit">Save</button>
</div>
</div>
</form>
当我确认一张表格时,我有一个例外,我不知道怎么了:
Failed to convert property value of type 'java.lang.Integer' to required type 'pl.sosinski.nutritioncounter.model.FoodProduct' for property 'foodProduct';
nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.Integer' to required type 'pl.sosinski.nutritioncounter.model.FoodProduct' for property 'foodProduct': no matching editors or conversion strategy found
org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.Integer' to required type 'pl.sosinski.nutritioncounter.model.FoodProduct' for property 'foodProduct'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.Integer' to required type 'pl.sosinski.nutritioncounter.model.FoodProduct' for property 'foodProduct': no matching editors or conversion strategy found
1条答案
按热度按时间wkyowqbh1#
如果你改变主意
foodProduct
选择代码如下,问题将得到解决。import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class StringToFoodProductConverter implements Converter<String, FoodProduct> {
}