Reputation: 427
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?
Upvotes: 1
Views: 1230
Reputation: 5327
Query selectAll = em.createQuery("SELECT p.nome FROM Persone p");
As you code shows you are selecting only string from query not all person object Following query will return person object
Query selectAll = em.createQuery("SELECT p FROM Persone p");
List<Persone> list = selectAll.getResultList();
If you want to select only name from person.A name is string type and it will return List<String>
Query selectAll = em.createQuery("SELECT p.nome FROM Persone p");
List<String> result = selectAll.getResultList();
Upvotes: 1
Reputation: 427
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 :)
Upvotes: 0
Reputation: 809
You are selecting the name (p.nome
) which is a string, so you'll get a string back.
If you want a whole person to be returned, select the whole person (SELECT p FROM Personne p
).
Upvotes: 4