В моем проекте две 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;
}
}
Лишнее удалено. У меня есть форма в шаблоне thymeleaf для Location, привожу часть, ответственную за редактирование 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>
В результате выполнения получаю ошибку:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'organization' available as request attribute
Проблема с th:field, ибо он в фрагменте он не видит форму, как я поняла. Подскажите, как забороть сие? Может быть для многократного использования шаблонов themeleaf в формах есть другой способ, помимо фрагментов?