简体   繁体   中英

Create typed query through the session factory in JPA/Hibernate

I generally want to do something like this:

CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Person> c = qb.createQuery(Person.class);

But through the session factory rather than the entity manager.

Something like:

final TypedQuery<MyType> query = getSessionFactory().getCurrentSession().createTypedQuery(MyType.class, "query");

It should be trivial, but for some reason I couldn't find info on how to do it (if it is at all possible, but I think it should be).

Thanks,

It is impossible, because Session doesn't have any method that returns instance of javax.persistence.TypedQuery. Having org.hibernate.Query to implement javax.persistence.TypedQuery would have been quite a surprise, because they are different beasts (kind of part of different API inside Hibernate). Just for being in safe side I also checked from source.

I don't believe there is such a method on Hibernate Session. Why not use EntityManager? It is part of JPA and therefore a Java EE standard?

If you are using Spring (Not my personal choice) you can use HibernateTemplate which hides the cast from you and provides type safe methods.

The cast is always going to happen somewhere!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM