简体   繁体   中英

Typed queries for non-entity results with JPQL

TypedQuery<UserNameAndPostCount> query = entityManager.createQuery(
  "select new com.loki2302.JPQLTest$UserNameAndPostCount" + 
  "(u.userName, count(p.id)) " +
  "from User u " + 
  "left join u.posts p group by u.userName", UserNameAndPostCount.class);

List<UserNameAndPostCount> resultList = query.getResultList();

Is there any "official" way to do the same without hardcoding com.loki2302.JPQLTest$UserNameAndPostCount in JPQL query text?

A query like

entityManager.createQuery("SELECT u.userName, count(p.id) FROM User u LEFT JOIN u.posts p GROUP BY u.userName", UserNameAndPostCount.class);

would likely work on some JPA implementations, certainly DataNucleus JPA aims to do such things. After all, the last argument is the result class, so its basically saying create me objects of that type with these result fields as arguments (or use setters with names consistent with those two result fields), and you can easily enough put "AS {alias}" in the select clause to get the result fields to match bean property names in the result class.

to avoid this hard coding you can use createNamedQuery(String) of entityManager interface. to use this method you have to create NamedQueries in your model(entity class) and use Query object instead TypedQuery.

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