java.lang.Object 无法投射

java.lang.Object cannot be cast

我正在尝试让所有用户对自定义问题中的消息投票:

List<Vote> list = sessionFactory.getCurrentSession()
        .createQuery("from Vote as v left join v.message as m " +
                "where m.question=:question and v.user=:user and v.voteType=:voteType")
        .setParameter("question", question)
        .setParameter("user", user)
        .setParameter("voteType", VoteType.MESSAGE)
        .list();
System.out.println(list.get(0).getMessage().getNumber());

并在最后一个字符串中出现异常:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to ru.kapahgaiii.qa.domain.Vote ru.kapahgaiii.qa.repository.ChatDAOImpl.getVotes(ChatDAOImpl.java:114)

我做错了什么?

Vote.java:

@Entity
@Table(name = "votes")
public class Vote {

    @Id
    @GeneratedValue
    @Column(name = "vote_id")
    private Integer voteId;

    @ManyToOne
    @JoinColumn(name = "uid")
    private User user;

    @Column(name = "vote_type", length = 8)
    @Enumerated(EnumType.STRING)
    private VoteType voteType;

    @ManyToOne
    @JoinColumn(name = "message_id")
    private Message message;

你投错了。 Hibernate returns 你所有的对象都按照你的要求查询。但是您需要使用索引 0 处的 Vote 对象。

List<Object[]> list = sessionFactory.getCurrentSession()
        .createQuery("from Vote as v left join v.message as m " +
                "where m.question=:question and v.user=:user and v.voteType=:voteType")
        .setParameter("question", question)
        .setParameter("user", user)
        .setParameter("voteType", VoteType.MESSAGE)
        .list();
System.out.println(list.get(0)[0].getMessage().getNumber());

尝试这样做:

List<Object> list = sessionFactory.getCurrentSession()
            .createQuery("from Vote as v left join v.message as m " +
                    "where m.question=:question and v.user=:user and v.voteType=:voteType")
            .setParameter("question", question)
            .setParameter("user", user)
            .setParameter("voteType", VoteType.MESSAGE)
            .list();
    System.out.println(((Vote) list.get(0)).getMessage().getNumber())

;