如何使用 CrudRepository 和 thymeleaf 实现多对一关系?

How can I achieve a manytoone relation using the CrudRepository and thymeleaf?

我正在使用 JPA 和 CrudRepository。我在客户和账单之间有一对多的关系。客户逐渐收到我要分配给客户的账单。

<div class="col-lg-3">
    <select name="customers" class="form-control m-bot15" required="">
        <option value="">*** Bitte auswählen ***</option>
        <option th:each="customer : ${customers}" th:value="${customer.customerID}" th:text="${customer.name}"></option>
    </select>
</div>

我在表单中使用此片段来显示客户并通过引用其名称插入 ID。

现在我有一个多对一的关系,因此有一个对象。有了这个,我无法设置 ID。

@ManyToOne(cascade = CascadeType.ALL)
private Customers customers;

我相信您在处理 spring 数据中的多对一关系方面没有任何问题。如果你这样做,你可以参考 中的解决方案。

让我们讨论如何根据用户从下拉列表中的选择分配 Id 并传递给控制器​​。

示例 1

我的语音代码。 注意:不要使用原始数据类型,如 int 或 long.It 如果用户没有选择任何东西, thymeleaf 将给 thymeleaf 分配空值带来麻烦。

private Long selectedCustomerId;
private Set<Customer> customerSet=new HashSet<Customer>();

Thymeleaf 代码。基于用户选择,thymeleaf 将 customerid 分配给 VO

selectedCustomerId 属性
<select id="customer-title" name="customer-title" th:field="*{selectedCustomerId}" th:required="required" class="form-control">                     
        <option value="" th:text="-Select-"></option>
        <option th:each="temp : *{customerSet}" 
            th:value="${temp.customerId}"  
            th:text="${temp.customerName}">
        </option>
</select>

示例 2 - 隐藏输入字段

Onchange 事件的下拉和 onload 的形式,你可以通过 javascript 将下拉列表中的选定值设置为隐藏的输入字段,反之亦然。

<input id="customer-id" name="customer-id" type="hidden" th:field="*{selectedCustomerId}"/>     
....
<select id="customer-title" name="customer-title" th:required="required" class="form-control">                      
            <option value="" th:text="-Select-"></option>
            <option th:each="temp : *{customerSet}" 
                th:value="${temp.customerId}"  
                th:text="${temp.customerName}">
            </option>
    </select>