ClassCastException в JpaRepository с использованием Kotlin

Я пытаюсь создать службу для обработки всех невыполненных ставок в игре со ставками, как только станет известен результат матча. Я получаю ClassCastException, когда пытаюсь использовать результаты запроса в JpaRepository.

Вот интерфейс и реализация моего сервиса

package com.github.juanmougan.prode.services

import com.github.juanmougan.prode.models.Match

interface MatchesService {
    fun processBetsForMatch(match: Match)
}


package com.github.juanmougan.prode.services

import com.github.juanmougan.prode.models.Bet
import com.github.juanmougan.prode.models.Match
import com.github.juanmougan.prode.repositories.BetsRepository
import org.springframework.stereotype.Service

@Service("messageService")
class MatchesServiceImpl(
                        val betsRepository: BetsRepository
                        ) : MatchesService {
    override fun processBetsForMatch(match: Match) {
        val unfulfilledBets: List<Bet> = betsRepository.findAllByMatchWhereBetHasNotBeenPlayed(match)
        unfulfilledBets.forEach { b ->
            b.played = true
            b.counted = true
            if (match.result?.equals(b.result)!!) {
                b.pointsWon = 1
            }
        }
    }
}

Также репозиторий

package com.github.juanmougan.prode.repositories

import com.github.juanmougan.prode.models.Bet
import com.github.juanmougan.prode.models.Match
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.query.Param

interface BetsRepository : JpaRepository<Bet, Long> {
    @Query("SELECT b.id, b.match, b.result, b.player, b.played, b.counted, b.pointsWon " +
            "FROM Bet b where b.match = :match and b.played = false")
    fun findAllByMatchWhereBetHasNotBeenPlayed(@Param("match") match: Match): List<Bet>
}

Я пробовал также с версией Java, безуспешно

package com.github.juanmougan.prode.repositories;

import com.github.juanmougan.prode.models.Bet;
import com.github.juanmougan.prode.models.Match;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface BetsRepository extends JpaRepository<Bet, Long> {
    @Query("SELECT b.id, b.match, b.result, b.player, b.played, b.counted, b.pointsWon " +
            "FROM Bet b where b.match = :match and b.played = false")
    List<Bet> findAllByMatchWhereBetHasNotBeenPlayed(@Param("match")Match match);
}

И, наконец, объект Bet, представляющий собой Java POJO

package com.github.juanmougan.prode.models;

import javax.persistence.*;

@Entity
public class Bet {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @ManyToOne
    private Match match;
    private Result result;
    @ManyToOne
    private Person player;
    private Boolean played;
    private Boolean counted;
    private Integer pointsWon;

    public Bet() {
    }

    public Bet(Match match, Result result, Person player, Boolean played, Boolean counted, Integer     pointsWon) {
        this.match = match;
        this.result = result;
        this.player = player;
        this.played = played;
        this.counted = counted;
        this.pointsWon = pointsWon;
    }

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

        Bet bet = (Bet) o;

        if (id != null ? !id.equals(bet.id) : bet.id != null) return false;
        if (match != null ? !match.equals(bet.match) : bet.match != null) return false;
        if (result != bet.result) return false;
        if (player != null ? !player.equals(bet.player) : bet.player != null) return false;
        if (played != null ? !played.equals(bet.played) : bet.played != null) return false;
        if (counted != null ? !counted.equals(bet.counted) : bet.counted != null) return false;
        return pointsWon != null ? pointsWon.equals(bet.pointsWon) : bet.pointsWon == null;
    }

    @Override
    public int hashCode() {
        int result1 = id != null ? id.hashCode() : 0;
        result1 = 31 * result1 + (match != null ? match.hashCode() : 0);
        result1 = 31 * result1 + (result != null ? result.hashCode() : 0);
        result1 = 31 * result1 + (player != null ? player.hashCode() : 0);
        result1 = 31 * result1 + (played != null ? played.hashCode() : 0);
        result1 = 31 * result1 + (counted != null ? counted.hashCode() : 0);
        result1 = 31 * result1 + (pointsWon != null ? pointsWon.hashCode() : 0);
        return result1;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Match getMatch() {
        return match;
    }

    public void setMatch(Match match) {
        this.match = match;
    }

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    public Person getPlayer() {
        return player;
    }

    public void setPlayer(Person player) {
        this.player = player;
    }

    public Boolean getPlayed() {
        return played;
    }

    public void setPlayed(Boolean played) {
        this.played = played;
    }

    public Boolean getCounted() {
        return counted;
    }

    public void setCounted(Boolean counted) {
        this.counted = counted;
    }

    public Integer getPointsWon() {
        return pointsWon;
    }

    public void setPointsWon(Integer pointsWon) {
        this.pointsWon = pointsWon;
    }
}

Исключение, которое я получаю:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.github.juanmougan.prode.models.Bet
at com.github.juanmougan.prode.services.MatchesServiceImpl.processBetsForMatch(MatchesServiceImpl.kt:31) ~[classes/:na]
at com.github.juanmougan.prode.controllers.MatchesController$updateById$1.apply(MatchesController.kt:34) ~[classes/:na]
at com.github.juanmougan.prode.controllers.MatchesController$updateById$1.apply(MatchesController.kt:12) ~[classes/:na]
at java.util.Optional.map(Optional.java:215) ~[na:1.8.0_66]
at com.github.juanmougan.prode.controllers.MatchesController.updateById(MatchesController.kt:31) ~[classes/:na]

Список, возвращаемый репозиторием, содержит объекты, несмотря на то, что он набран с помощью Bet.
. Любые идеи?

Похоже, это связано с этим вопросом, stackoverflow.com/questions/23122846/…

Fabri Pautasso 14.06.2018 00:55

Большое спасибо @FabriPautasso! Изменение запроса на SELECT b FROM Bet b where b.match = :match and b.played = false было решением

jmm 14.06.2018 01:25
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Версия Java на основе версии загрузки
Версия Java на основе версии загрузки
Если вы зайдете на официальный сайт Spring Boot , там представлен start.spring.io , который упрощает создание проектов Spring Boot, как показано ниже.
Документирование API с помощью Swagger на Springboot
Документирование API с помощью Swagger на Springboot
В предыдущей статье мы уже узнали, как создать Rest API с помощью Springboot и MySql .
0
2
233
0

Другие вопросы по теме