Search code examples
javasqljpajpql

JPQL Query - java.lang.String cannot be cast to model.xxx


ACTUAL FULL ERROR

java.lang.ClassCastException: java.lang.String cannot be cast to model.Persone

--

Hi al, I'm very new to JPQL and I'm trying to write a quite simple JPQL Query without luck.

I have a database table named persone with the a String nome column.

The query I'd like to translate is SELECT Nome FROM persone

--

Here's the entity

@Entity
public class Persone implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id_persona")
    private int idPersona;

    private String cognome;

    private Timestamp data_nascita;

    @Column(name="nome")
    private String nome;
}

--

This is a snippet of the query execution method. I tried to modify it setting the return (and everything else) to String instead of List, but then I can't manage to get the right method instead of getResultList().

public static List<Persone> selectAllPersone(){
    Query selectAll = em.createQuery("SELECT p FROM Persone p");
    @SuppressWarnings("unchecked")
    List<Persone> list = selectAll.getResultList();
    return list;
}

--

And here's me failing at coding

Query selectAll = em.createQuery("SELECT p.nome FROM Persone p");

What could this error be due to?


Solution

  • I managed to sort it out and have it work for me. I just created a new method which returns a List<String> and it went fine.

    public static List<String> selectNome(){
        Query selectAll = em.createQuery("SELECT p.nome FROM Persone p");
        @SuppressWarnings("unchecked")
        List<String> qnome = selectAll.getResultList();
        return qnome;
    }
    

    Thank you guys for your help :)