I use hibernate-4.2.3 and i will run my first NamedQuery
. i create it as below:
@NamedQuery(name="LoadUserWithEmail",query="select u from User u where email=:email")
after that i get it with session.createNamedQuery
:
SessionFactory sessionFactory=SessionFactoryBuilder.build();
Session session=sessionFactory.openSession();
javax.persistence.Query query= (javax.persistence.Query) session.getNamedQuery("LoadUserWithEmail");
query.setParameter("email", email);
User user= (User) query.getSingleResult();
but when i run this code i get following error:
Exception in thread "main" java.lang.ClassCastException: org.hibernate.internal.QueryImpl cannot be cast to javax.persistence.Query
at ir.sarresid.persistence.dao.UserDaoImpl.getWithEmail(UserDaoImpl.java:15)
at ir.sarresid.persistence.test.PersonTest.getUser(PersonTest.java:51)
at ir.sarresid.persistence.test.PersonTest.main(PersonTest.java:17)
how i can solve it. i will not use org.hibernate.Query.
Do you have any solution. thanks.
It looks like you are mixing Hibernate-specific types and annotations with JPA types and annotations. SessionFactory and Session are Hibernate-specific classes, and session.getNamedQuery()
returns an object that implements org.hibernate.Query
, not javax.persistence.Query
.
On the other hand, javax.persistence.Query
is a JPA class and will be returned if you create the named query using JPA's EntityManager, e.g.:
javax.persistence.Query query = entityManager.createNamedQuery("LoadUserWithEmail");
Note also that there is a org.hibernate.annotations.NamedQuery
and a javax.persistence.NamedQuery
.
It is usually simpler to not mix the types and annotations of the two interfaces (SessionFactory vs JPA). If you use SessionFactory, you should stick with the Hibernate-specific types.