Reputation: 37
I'm using hibernate to interact with my DataBase, which is a MySQL DB. I can write in it with EntityManager, but when I want to query my DB and get some infos, I always get this error:
java.lang.ClassCastException
:[Ljava.lang.Object;
cannot be cast tocom.projetJava.NoteTonSTA.model.Speakers
Speakers
is my entity. Like I said I manage to persist it without any problems.
Here is a part of my code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String password = request.getParameter("password");
String queriedPass = null;
EntityManager em = emf.createEntityManager(); //emf is declared before. It's an EntityManagerFactory object.
try {
Query querySpeaker = (Query) em.createQuery("SELECT s.password, s.email, s.first_name, s.last_name FROM Speakers s WHERE email=:login");
querySpeaker.setParameter("login", login);
Speakers auth = (Speakers) querySpeaker.getSingleResult();
}
I get the login from my login page. I'm sure it exists (it doesn't throw 'no results' exeption).
The request seems to be good but he's not able to execute the last line, and cast properly.
Upvotes: 1
Views: 98
Reputation: 403481
If you specify a list of specific properties in your SELECT
(i.e. SELECT s.password, s.email, s.first_name, s.last_name
), then Hibernate will return an array containing just those properties, rather than the entire entity. This is why you get the ClassCastException
.
To get the entity, omit the SELECT
clause, e.g.
em.createQuery("FROM Speakers WHERE email=:login");
Upvotes: 3