@Espio

Как правильно работать с ManyToMany в Spring?

Добрый день не получается наладить добавление записей в ManyToMany. Вот код
Класс GameRoom
@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long idGameRoom;
    private String nameGameRoom;
    private String dateGameRoom;
    private String cityGameRoom;
    private String adressGameRoom;
    private String discriptionGameRoom;
    private String filenameGameRoom;
    private int countPeople;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToMany(cascade = {
            CascadeType.PERSIST,
            CascadeType.MERGE
    })
    @JoinTable(
            name = "tablegames_to_gameroom",
            joinColumns = {@JoinColumn(name = "gameroom_id")},
            inverseJoinColumns = {@JoinColumn(name = "tablegame_id")}
    )
    private Set<TableGames> tableGames = new HashSet<>();



    public Set<TableGames> getTableGames() {
        return tableGames;
    }

    public void setTableGames(Set<TableGames> tableGames) {
        this.tableGames = tableGames;
    }

    public void addTableGames(TableGames tableGame){
        this.tableGames.add(tableGame);
        tableGame.getGamesRooms().add(this);
    }


Класс TableGames
@Entity
public class TableGames {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long idTableGames;
    private String nameTableGames;
    private String discriptionTableGames;
    private String filenameTableGames;


    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "tableGames")
    private Set<GamesRoom> gamesRooms = new HashSet<>();

    public Set<GamesRoom> getGamesRooms() {
        return gamesRooms;
    }

    public void setGamesRooms(Set<GamesRoom> gamesRooms) {
        this.gamesRooms = gamesRooms;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        TableGames that = (TableGames) o;
        return gamesRooms.equals(that.gamesRooms);
    }


Часть контроллера который пытаюсь отладить
@PostMapping("/gamerooms")
    public String addRoom(
            @AuthenticationPrincipal User user,
            @RequestParam String nameGameRoom,
            @RequestParam String dateGameRoom,
            @RequestParam String cityGameRoom,
            @RequestParam String adressGameRoom,
            @RequestParam String discriptionGameRoom,
            @RequestParam int countPeople,
            @RequestParam Set<TableGames> gamesSet,
            @RequestParam ("filenameGameRoom") MultipartFile filenameGameRoom,
            Model model
    )throws IOException {

        gameRoomService.addGameRoom(user, nameGameRoom, discriptionGameRoom, countPeople, dateGameRoom, cityGameRoom, adressGameRoom, filenameGameRoom, gamesSet);

        model.addAttribute("tablegames", gamesRepo.findAll());
        model.addAttribute("gamesroom", gameRoomService.findAll());
        return "gameroomsList";
    }

Собственно логика добавления в в классе сервиса
public boolean addGameRoom(
            User user,
            String nameGameRoom,
            String discriptionGameRoom,
            int countPeople,
            String dateGameRoom,
            String cityGameRoom,
            String adressGameRoom,
            MultipartFile filenameGameRoom,
            Set<TableGames> gamesSet
    )throws IOException{
        GamesRoom gamesRoom = new GamesRoom(
                nameGameRoom,
                dateGameRoom,
                cityGameRoom,
                adressGameRoom,
                discriptionGameRoom,
                user,
                countPeople);

        Iterator<TableGames> iterator = gamesSet.iterator();
        while (iterator.hasNext()){
            gamesRoom.addTableGames(iterator.next());
        }

        if (filenameGameRoom != null && !filenameGameRoom.getOriginalFilename().isEmpty()) {
            File uploadDir = new File(uploadPath);

            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            String uuidFile = UUID.randomUUID().toString();
            String resultFilename = uuidFile + "." + filenameGameRoom.getOriginalFilename();

            filenameGameRoom.transferTo(new File(uploadPath + "/" + resultFilename));

            gamesRoom.setFilenameGameRoom(resultFilename);
        }

        gameRoomRepo.save(gamesRoom);
        return true;
    }

То как я передаю параметр со странице (в будущем поменяю на select пока сделал так для отладки)
<div class="form-group">
                        <label for="exampleFormControlSelect2">Во что играем?</label>
                            <#list tablegames>
                                <#items as game>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" value="${game.idTableGames}" id="defaultCheck1" name="gamesSet">
                                        <label class="form-check-label" for="defaultCheck1">
                                            ${game.nameTableGames}
                                        </label>
                                    </div>
                                 </#items>
                            </#list>
                        </select>
                    </div>

Собственно возникающая ошибка.
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Jun 08 20:30:28 YEKT 2021
There was an unexpected error (type=Internal Server Error, status=500).
java.lang.String cannot be cast to com.example.deeplom.domain.TableGames
java.lang.ClassCastException: java.lang.String cannot be cast to com.example.deeplom.domain.TableGames
	at com.example.deeplom.service.GameRoomService.addGameRoom(GameRoomService.java:63)
	at com.example.deeplom.controllers.GameRoomContoller.addRoom(GameRoomContoller.java:59)
	at com.example.deeplom.controllers.GameRoomContoller$$FastClassBySpringCGLIB$$78999585.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:685)
	at com.example.deeplom.controllers.GameRoomContoller$$EnhancerBySpringCGLIB$$7ff959.addRoom(<generated>)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Я не могу понять что я делаю не так, что и где стоит поправить?
  • Вопрос задан
  • 164 просмотра
Пригласить эксперта
Ответы на вопрос 1
azerphoenix
@azerphoenix Куратор тега Java
Java Software Engineer
Добрый день.
Читали ли вы лог ошибок?
ClassCastException: java.lang.String cannot be cast to com.example.deeplom.domain.TableGames

Ошибка приведения типов. Тип String не может быть приведен к типу TableGames.
Притом исключение выбрасывается в методе: addGameRoom()
Поставьте точки остановки и проведите дебаг проекта
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽
23 апр. 2024, в 15:45
10000 руб./за проект
23 апр. 2024, в 15:42
5000 руб./за проект
23 апр. 2024, в 15:34
10000 руб./за проект