2017-04-16 44 views
1

我试图通过使用多个下拉菜单来从百里香传递产品ID列表。它输出大小,但产品对象为空。如果我在Expense类中创建List<String> product;并将expenseDetail替换为addExpense.htmlproduct;有用。我试图通过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"; 
    } 
} 

回答

0

在选择字段应该是你想要的选项(产品ID)去的价值,所以你应该使用th:field="*{expenseDetail[0].product.id}"

然后这会给你一个Product包含你的ExpenseDetail对象中选定的ID。如果在select中没有选择任何内容,那么您将在Product中得到一个空ID,您需要在服务器端处理这些ID或使用JavaScript排除该字段为空。

请记住,Thymeleaf对您的Product物体或其来源不了解。它只会填充表单中显示的字段,所以其他内容如name在POST处理程序中将为空。通常情况下,您只需拿到ID并使用它从数据库或其他任何地方重新加载对象。