我试图通过使用多个下拉菜单来从百里香传递产品ID列表。它输出大小,但产品对象为空。如果我在Expense
类中创建List<String> product;
并将expenseDetail
替换为addExpense.html
与product
;有用。我试图通过ExpenseDetail
类从百里香到弹簧启动的对象列表
消费类
@Entity
public class Expense {
//fields
@OneToMany(mappedBy = "expense", cascade = CascadeType.ALL)
@NotNull
private List<ExpenseDetail> expenseDetail;
//getters and setters
}
ExpenseDetail类
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 -->
ExpenseController
@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";
}
}