【发布时间】:2017-09-12 05:54:08
【问题描述】:
我正在尝试通过使用多个下拉菜单从 thymeleaf 传递产品 ID 列表。它输出大小,但产品对象为空。如果我在Expense 类中创建List<String> product; 并将addExpense.html 中的expenseDetail 替换为product;有用。我正在尝试通过ExpenseDetail 类传递产品
费用类别
@Entity
public class Expense {
//fields
@OneToMany(mappedBy = "expense", cascade = CascadeType.ALL)
@NotNull
private List<ExpenseDetail> expenseDetail;
//getters and setters
}
费用明细类
public class ExpenseDetail {
//fields
@ManyToOne
@JoinColumn(name = "expense_id")
private Expense expense;
@ManyToOne
@JoinColumn(name = "product_id")
private Product product;
//getters and setters
}
addExpense.html
<form th:action="@{/expense/new}" th:method="post" th:object="${expense}">
<select id="product" th:field="*{expenseDetail[0]}">
<option value="" th:text="#{item.select.prompt}"></option>
<option th:each="product: ${products}" th:value="${product.id}" th:text="${product.name}"></option>
</select>
<select id="product" th:field="*{expenseDetail[1]}" >
<option value="" th:text="#{item.select.prompt}"></option>
<option th:each="product: ${products}" th:value="${product.id}" th:text="${product.name}"></option>
</select>
<button type="submit" name="Save expense">Save Expense</button>
</form><!-- ends expense form -->
费用控制器
@Controller
public class ExpenseController {
@PostMapping("/expense/new")
public String addExpense(@Valid Expense expense, BindingResult result, Model model){
//This prints the list of size 2
System.out.println(expense.getExpenseDetail().size());
List<ExpenseDetail> el=expense.getExpenseDetail();
el.forEach(e->{
System.out.println(e.getProduct()); //this is null
});
return "addExpense";
}
}
【问题讨论】:
标签: java spring-mvc spring-boot thymeleaf