Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypedQuery instead of normal Query in JPA

Is it possible to write this Query as a TypedQuery and let the two Long's run into a Object with two public Long fields inside.

    Query q = em.createQuery(
            "SELECT c.id, COUNT(t.id) " +
            "FROM PubText t " +
            "JOIN t.comm c " +
            "WHERE c.element = ?1 " +
            "GROUP BY c.id");
    q.setParameter(1, e);
    List<?> rl = q.getResultList();
    Iterator<?> it = rl.iterator();
    HashMap<Long, Long> res = new HashMap<Long, Long>();
    while (it.hasNext()) {
        Object[] n = (Object[]) it.next();
        res.put((Long)n[0], (Long)n[1]);
    }
    return res;
like image 610
Hasan Tuncay Avatar asked Mar 14 '13 15:03

Hasan Tuncay


People also ask

What is TypedQuery in JPA?

But, JPA provides a special Query sub-type known as a TypedQuery. This is always preferred if we know our Query result type beforehand. Additionally, it makes our code much more reliable and easier to test. This way, we get stronger typing for free, avoiding possible casting exceptions down the road.

What is the difference between query and TypedQuery?

TypedQuery gives you an option to mention the type of entity when you create a query and therefore any operation thereafter does not need an explicit cast to the intended type. Whereas the normal Query API does not return the exact type of Object you expect and you need to cast.

Which is faster JPQL or native query?

Also, JPA criteria queries are as fast as JPQL queries, and JPA native queries have the same efficiency as JPQL queries. This test run has 11008 records in the Order table, 22008 records in the LineItem table, and 44000 records in the Customer table.

Which is better JPQL or native query?

JPQL is the most commonly used query language with JPA and Hibernate. It provides an easy way to query data from the database. But it supports only a small subset of the SQL standard, and it also does not support database-specific features. If you want to use any of these features, you need to use a native SQL query.


1 Answers

JPA has a feature just for this - constructor expressions:

Query q = entityManager.createQuery("SELECT NEW com.example.DTO( c.id, COUNT(t.id)) FROM ...");
List<DTO> dtos = q.getResultList();

Your DTO class can be a POJO. All it will need is a public constructor accepting 2 Longs. Please note that you have to provide a fully qualified name of your class after the NEWoperator.

like image 60
kostja Avatar answered Sep 26 '22 09:09

kostja