복붙노트

[SPRING] 자동 채우기 집합

SPRING

자동 채우기 집합

AutoPopulatingList와 같은 것이 있습니까? 표시하고자하는 데이터는 Set을 사용하는 연관입니다.

public class Employer implements java.io.Serializable {
     private Set<Employee> employees = new HashSet();
}

나는 AutoPopulatingList를 사용하려고 시도했으나이 경우 필자는 Employee.employeeId를 사용하여 목록 인덱스를 지정해야하는 최대 절전 모드에서 List를 사용해야하고 나중에 Employee를 통해 직원을 검색 할 때마다 목록에 요소 (null 요소) 사이에 공백이있을 것이다. Employee.employeeId에 있습니다.

고용주를 생성하는 동안 직원을 동적으로 생성해야하기 때문에 컬렉션을 자동으로 채워야합니다. 나는 일반 세트를 사용할 때 다음을 얻는다. org.springframework.beans.InvalidPropertyException : bean 클래스 [models.Employer]의 'employees [0]'속성이 올바르지 않습니다. 속성 경로 'employees [0]'을 사용하여 액세스 한 크기 0의 집합에서 인덱스 0 인 요소를 가져올 수 없습니다.

다른 해결책이 있습니까?

편집하다

동적 양식을 구현하려고합니다.

해결법

  1. ==============================

    1.해당 항목에 대한 속성 경로를 만들 수 없기 때문에 Set를 MVC에서 바인딩 대상으로 사용할 수 없습니다.

    해당 항목에 대한 속성 경로를 만들 수 없기 때문에 Set를 MVC에서 바인딩 대상으로 사용할 수 없습니다.

    동적 양식을 작성할 때는 Map 을 사용해야합니다. 우리가 여러 번 구현 한 것들 (그래서 나는 그것이 작동하고 있음을 안다)은 이것이다 :

    이 작업을 수행하는 방법에는 여러 가지가 있습니다. 예를 들어 우리는 다른 템플릿을 동적으로 추가해야 할 때 사용되는 특별한 템플릿 하위 폼을 가지고 있습니다. 이 접근법은 다음과 같이 약간 더 복잡합니다.

    <form:form action="${formUrl}" method="post" modelAttribute="organizationUsersForm">
        <%-- ... other fields ... --%>
        <div id="userSubforms">
            <c:forEach items="${organizationUsersForm.users.entrySet()}" var="subformEntry">
                <div data-subform-key="${subformEntry.key}">
                    <spring:nestedPath path="users['${subformEntry.key}']">
                        <%@ include file="user-subform.jspf" %>
                    </spring:nestedPath>
                </div>
            </c:forEach>
        </div>
        <button onclick="addSubform(jQuery('#userSubforms'), 'users', 'user', 'userTemplate');">ADD ANOTHER USER</button>
        <%-- other form fields, submit, etc. --%>
    </form:form>
    
    <div class="hide" data-subform-template="user">
        <spring:nestedPath path="userTemplate">
            <%@ include file="user-subform.jspf" %>
        </spring:nestedPath>
    </div>
    
    <script>
        function addSubform(subformContainer, subformPath, templateName, templatePath) {
            // Find the sequence number for the new subform
            var existingSubforms = subformContainer.find("[data-subform-key]");
            var subformIndex = (existingSubforms.length != 0) ?
                    parseInt(existingSubforms.last().attr("data-subform-key"), 10) + 1 : 0;
            // Create new subform based on the template
            var subform = jQuery('<div data-subform-key="' + subformIndex + '" />').
                    append(jQuery("[data-subform-template=" + templateName + "]").children().clone(true));
            // Don't forget to update field names, identifiers and label targets
            subform.find("[name]").each(function(node) {
                this.name = subformPath + "["+ subformIndex +"]." + this.name;
            });
            subform.find("[for^=" + templatePath + "]").each(function(node) {
                this.htmlFor = this.htmlFor.replace(templatePath + ".", subformPath + "["+ subformIndex +"].");
            });
            subform.find("[id^=" + templatePath + "]").each(function(node) {
                this.id = this.id.replace(templatePath + ".", subformPath + "["+ subformIndex +"].");
            });
            // Add the new subform to the form
            subformContainer.append(subform);
        }
    </script>
    

    이제 "어떻게 사용자가 하위 양식을 삭제할 수 있습니까?"라는 질문을 할 수 있습니다. 하위 폼 JSPF에 다음과 같은 내용이 포함 된 경우 매우 간단합니다.

    <button onclick="jQuery(this).parents('[data-subform-key]').remove();">DELETE USER</button>
    
  2. ==============================

    2.Set은 인덱싱 된 컬렉션이 아니며 인덱싱 된 컬렉션 또는 배열 만 바인딩 할 수 있습니다. LinkedHashSet (HashSet이 아닌 반면 보증 된 순서를 가짐)을 사용하거나 List 구현을 사용하여 값을 바인딩 할 수 있습니다.

    Set은 인덱싱 된 컬렉션이 아니며 인덱싱 된 컬렉션 또는 배열 만 바인딩 할 수 있습니다. LinkedHashSet (HashSet이 아닌 반면 보증 된 순서를 가짐)을 사용하거나 List 구현을 사용하여 값을 바인딩 할 수 있습니다.

  3. ==============================

    3."인덱스가 0 인 요소를 가져올 수 없습니다.".. 집합은 인덱스를 기반으로 시작하지 않습니다.

    "인덱스가 0 인 요소를 가져올 수 없습니다.".. 집합은 인덱스를 기반으로 시작하지 않습니다.

    왜 LazyList of Employee를 사용하지 않습니까? @PavelHoral이 가리키는대로 LazyList를 사용할 필요가 없습니다. Spring에서 처리 할 때 LazyList를 사용할 필요가 없습니다. 새 ArrayList ()와 같은 간단한 List 초기화가 가능하지만 사용자가 불연속 요소를 제출할 때 공백 (nulls)이 있음을 나타냅니다.

    private List<Employee> employees = new ArrayList<Employee>();
    
  4. from https://stackoverflow.com/questions/17002027/auto-populating-set by cc-by-sa and MIT license