【问题标题】:How can I achieve a manytoone relation using the CrudRepository and thymeleaf?如何使用 CrudRepository 和 thymeleaf 实现多方关系?
【发布时间】:2016-03-31 09:33:09
【问题描述】:

我将 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>

我在表单中使用这个 sn-p 来显示客户并通过引用其名称来插入 ID。

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

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

【问题讨论】:

  • 不清楚你不想做什么。向您发布entity 代码或您希望作为结果获得的界面示例。
  • 您使用的是哪种映射?在什么情况下有效,在什么情况下无效(适用于哪个映射?)???

标签: java spring spring-boot spring-data-jpa thymeleaf


【解决方案1】:

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

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

示例1

我的 VO 代码。 注意:请勿使用 int 或 long 等原始数据类型。如果用户没有选择任何内容,则 thymeleaf 分配回 null 值会很麻烦。

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

百里香代码。根据用户选择,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事件和表单的加载,您可以通过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>

【讨论】:

    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 2013-12-03
    • 2018-07-19
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    相关资源
    最近更新 更多