在我的spring-mvc项目中,两个JPA实体具有不同名称的Organization属性:

@Entity
public class Video extends AbstractIdentifiable implements Serializable {
    @ManyToOne
    @JsonIgnore
    @JoinColumn(nullable = false)
    private Organization customerOrganization;

    public Organization getCustomerOrganization() {
        return customerOrganization;
    }

    public void setCustomerOrganization(Organization customerOrganization) {
        this.customerOrganization = customerOrganization;
    }
}

@Entity
public class Location extends AbstractIdentifiable implements Serializable {
    @ManyToOne
    @JoinColumn(nullable = false)
    @JsonIgnore
    private Organization organization;

    public Organization getOrganization() {
        return organization;
    }

    public void setOrganization(Organization organization) {
        this.organization = organization;
    }
}

不必要的被删除 . 我在位置的百万美元模板中有一个表单,给负责编辑组织的部分:

<div class="col-md-4 mb-3">
    <label for="organization" th:text="#{organization}"/>
    <select class="form-control" id="organization" name="organization" th:attrappend="class=${#fields.hasErrors('organization') ? ' is-invalid' : ''}" th:field="*{organization}">
        <option th:each="organization: ${organizations}" th:value="${organization.id}" th:text="${organization.title}"/>
    </select>
    <div class="invalid-feedback" th:if="${#fields.hasErrors('organization')}">
        <p th:each="error: ${#fields.errors('organization')}" th:text="${error}"/>
    </div>
</div>

我想在一个片段中取出它,用于存在此属性的所有实体,以便不复制和粘贴代码,考虑到实体可以具有不同的属性名称 . 上面给出的块替换为:

<div th:replace="~{forms :: organization('organization', *{organization})}"/>

分段:

<div th:fragment="organization(fieldName, organization)" class="col-md-4 mb-3">
    <label th:for="${fieldName}" th:text="#{organization}"/>
    <select th:id="${fieldName}" th:name="${fieldName}"
            th:attrappend="class=${#fields.hasErrors(fieldName) ? ' is-invalid' : ''}"
            th:field="${organization}" class="form-control">
        <option th:each="organization: ${organizations}" th:object="${organization}"
                th:value="*{id}"
                th:text="*{title}"/>
    </select>
    <div class="invalid-feedback" th:if="${#fields.hasErrors(${fieldName})}">
        <p th:each="error: ${#fields.errors(${fieldName})}" th:text="${error}"/>
    </div>
</div>

结果我收到错误:

<raw>java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'organization' available as request attribute

th:field的问题因为它在片段中没有看到我所理解的形式 . 如何修复这个?也许在表格中重复使用主题模板还有其他方式,除了片段?