Alexis_Shef_777
Alexis_Shef_777

Reputation: 133

I can’t transfer many objects through the controller(((

When I try to transfer a lot of data through the controller, I get an error:

There was an unexpected error (type=Bad Request, status=400). Failed to convert value of type 'java.lang.String' to required type 'com.psu.projectmethod.domain.wrappers.UserSet'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.ModelAttribute com.psu.projectmethod.domain.wrappers.UserSet] for value 'com.psu.projectmethod.domain.User@23'; nested exception is java.lang.IllegalArgumentException: Could not instantiate Collection type: com.psu.projectmethod.domain.wrappers.UserSet org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'com.psu.projectmethod.domain.wrappers.UserSet'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.ModelAttribute com.psu.projectmethod.domain.wrappers.UserSet] for value 'com.psu.projectmethod.domain.User@23'; nested exception is java.lang.IllegalArgumentException: Could not instantiate Collection type: com.psu.projectmethod.domain.wrappers.UserSet

I did everything according to examples from stackoverflow and based on this article https://www.viralpatel.net/spring-mvc-multi-row-submit-java-list/. Please help me fix this problem ((

My controller methods:

@PreAuthorize("hasAuthority('_2_TEACHER')")
@GetMapping("/project/{projectId}/party/create")
public String viewTeacherCreateProjectParty(
        @PathVariable("projectId") Project project,
        Party party,
        Model model) {
    Set<User> users = userService.userList(Sort.by("username"));
    UserSet userSet = new UserSet(users);
    model.addAttribute("project", project);
    model.addAttribute("party", party);
    model.addAttribute("users", userSet.getUsers());
    return "teacherProjectPartyCreate";
}

@PreAuthorize("hasAuthority('_2_TEACHER')")
@PostMapping("/project/{projectId}/party/create")
public String processCreateProjectParty(
        @PathVariable("projectId") Project project,
        @Valid Party party,
        @ModelAttribute("users") UserSet users,
        Model model) {
    model.addAttribute("project", project);
    model.addAttribute("party", party);
    Long projectId = projectService.createProjectParty(project, party, users);
    return "redirect:/projects/project/" + projectId;
}

Freemarker form:

<form action="/projects/project/${project.projectId}/party/create" method="post"
                          style="color: #757575;">

                        <!-- CSRF Token -->
                        <input type="hidden" name="_csrf" value="${_csrf.token}"/>

                        <div class="md-form">
                            <input type="text" id="partyName" name="partyName" value="${party.partyName!''}"
                                   class="form-control ${(partyNameError??)?string('is-invalid', '')}" required>
                            <label for="partyName">Group name</label>
                            <#if partyNameError??>
                                <div class="invalid-feedback">
                                    ${partyNameError}
                                </div>
                            </#if>
                        </div>

                        <select name="users" class="selectpicker"
                                data-header="Select users"
                                data-live-search="true"
                                data-selected-text-format="count"
                                data-size="auto"
                                data-style="btn-unique"
                                data-width="auto"
                                multiple
                                title="Select users"
                        >
                            <#list users as user>
                                <option value="${user}">${user.fullname}</option>
                            </#list>
                        </select>

                        <div class="modal-footer d-flex justify-content-center">

                            <button type="button" onClick='location.href="/projects/project/${project.projectId}"'
                                    class="btn btn-outline-info waves-effect">
                                Отмена
                            </button>

                            <button type="submit" class="btn btn-primary waves-effect">
                                Save
                            </button>

                        </div>

                    </form>

My Entity Creation Method

public Long createProjectParty(Project project, Party party, Set<User> users) {
    project.addParty(party);
    party.addUsers(party, users);
    projectRepo.save(project);
    return project.getProjectId();
}

Helper methods to add bi-directional associations:

public void addParty(Party party) {
    party.setPartyProject(this);
    this.projectParties.add(party);
}

public void addUsers(Party party, Set<User> users) {
    party.setPartyUsers(users);
    this.partyUsers.addAll(users);
}

ManyToMany association mapping:

@ManyToMany(fetch = FetchType.LAZY,
        cascade = {CascadeType.PERSIST, CascadeType.DETACH, CascadeType.REFRESH, CascadeType.REMOVE}
)
@JoinTable(name = "party_users",
        joinColumns = {@JoinColumn(name = "fk_party_id")},
        inverseJoinColumns = {@JoinColumn(name = "fk_user_id")})
private Set<User> partyUsers = new HashSet<>();

public class UserSet implements Set<User> {
private Set<User> users;

public UserSet(Set<User> users) {
    this.users = users;
}

public Set<User> getUsers() {
    return users;
}

public void setUsers(Set<User> users) {
    this.users = users;
}
... // getters, setters and Set metods 

Upvotes: 0

Views: 171

Answers (1)

Konstantin Kuzmin
Konstantin Kuzmin

Reputation: 37

After analysing your logs I've found that it's something bad with your request.

Read this log entry carefully:

Failed to convert value of type 'java.lang.String' to required type 'com.psu.projectmethod.domain.wrappers.UserSet'

It seems you're trying to send String in the place where it's expected UserSet. If this behavior is desired please consider to use Converters. Check the article

Upvotes: 0

Related Questions