在JSP中创建新对象到外键

时间:2017-12-05 13:10:50

标签: jsp spring-mvc

我在SQL中有两个对象和表格:员工和发票。 一名员工可以签发多张发票。 Invoice有一个Employee的外键。

我想创建视图(在JSP中),在添加发票时,将选择现有员工[来自SQL]表单下拉列表。但我不知道我怎么做"制造" JSP中的对象Employee。我这样做:

员工:

@Entity
@Table(name = "employee")
public class Employee {
 /.../

@OneToMany(mappedBy = "employee")
private List<Invoice> invoice;

发票:

  @Entity
    @Table(name = "invoice")
    public class Invoice {
           /.../
    @ManyToOne
    @JoinColumn(name="id_employee")
    private Employee employee;

InvoiceController:

@RequestMapping(value = "/invoice-add", method = RequestMethod.GET)
    public String addInvoice(Model model) {

        List<Employee> employeeList = employeeRepository.findAll();
        model.addAttribute("invoice", new Invoice());
        model.addAttribute("employeeList", employeeList);

        return "invoice-add";
    }

    @RequestMapping(value = "/invoice-add/save", method = RequestMethod.POST)
    public String saveInvoice(@ModelAttribute Invoice invoice, BindingResult result) {

        if (result.hasErrors()) {
            return "invoice-add";
        }
        invoiceRepository.save(invoice);
        return "redirect:/invoice";
    }

发票add.jsp:

<form:form modelAttribute="invoice" action="${invoiceAddURL}" method="post" role="form" class="form-horizontal">
/.../
      <div class="col-sm-6">
         <form:select path="employee">
         <c:forEach var="employee" items="${employeeList}">
         <form:option value="${employee.id}" label="${employee.name}" />
         </c:forEach>
         </form:select>

      </div>
</form:form>

...但它不起作用[错误:&#34; java.lang.IllegalStateException:既不是BindingResult也不是bean名称的普通目标对象&#39; invoice&#39;可用作请求属性&#34;。但当我删除与&#34;外键相关的代码时#34;有用]。你能告诉我怎么做吗?

0 个答案:

没有答案